二叉树中序找下一个元素

已知一颗二叉树 每个节点有指向左右子女的指针以及指向其父节点的指针,求在中序遍历该二叉树的情况下,给出一个节点,求它的下一个节点

分为三种情况:

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");
} 




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值