已知一颗二叉树 每个节点有指向左右子女的指针以及指向其父节点的指针,求在中序遍历该二叉树的情况下,给出一个节点,求它的下一个节点
分为三种情况:
1. 已知节点没有右子女,则下一个输出节点为其父节点
2. 已知节点没有右子女,它是父节点的右节点,则求下一个输出节点需要不断往上查找,直到一个节点是上一个节点的左子树
3. 已知节点有右子女,则下一个节点为其右子数的最左叶子节点
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node * left;
struct node * right;
struct node * parent;
}BTNode;
BTNode * CreateTree(int arr[],int n)
{
BTNode * t,*p,*q,*root=NULL;
for(int i=0;i<n;i++){
p=(BTNode *)malloc(sizeof(BTNode));
p->data=arr[i];
p->left=p->right=p->parent=NULL;
if(!root){
root=p;
}
else{
q=root;
while(q){
t=q;
if(q->data>p->data)
q=q->left;
else
q=q->right;
}
if(t->data>p->data)
t->left=p;
else
t->right=p;
p->parent=t;
}
}
return root;
}
void midPrint(BTNode * root)
{
if(root)
{
midPrint(root->left);
printf("%5d",root->data);
midPrint(root->right);
}
}
/*根据值查找节点*/
BTNode * findThisNode(BTNode * root,int thisNode)
{
BTNode * p=NULL;
if(root==NULL)
return NULL;
else{
if(thisNode>root->data)
p=findThisNode(root->right,thisNode);
else if(thisNode<root->data)
p=findThisNode(root->left,thisNode);
else if(thisNode==root->data)
p=root;
}
return p;
}
/*根据已知节点,找出中序遍历的呃呃该节点的下一个节点*/
void findNextNode(BTNode * thisNode)
{
if(thisNode->right!=NULL){
BTNode * q=thisNode->right;
while(q->left!=NULL)
q=q->left;
printf("下一个节点值:%d",q->data);
}
else if(thisNode->right==NULL&&thisNode->parent->left==thisNode){
printf("下一个节点值:%d",thisNode->parent->data);
}
else if(thisNode->right==NULL&&thisNode->parent->right==thisNode){
BTNode * q=thisNode;
while(q->parent->right==q){
q=q->parent;
if(q->parent==NULL){
printf("已经是最后一个节点了!\n");
break;
}
}
if(q->parent!=NULL)
printf("下一个节点值:%d",q->parent->data);
}
}
int main(void)
{
int arr[8]={5,2,3,8,4,7,6,9};
BTNode * root,*thisNode;
root=CreateTree(arr,8);
thisNode=findThisNode(root,9);
findNextNode(thisNode);
printf("\n中序遍历:\n");
midPrint(root);
printf("\n");
}