二叉树的下一个节点

第八个题目,题目如下:
在这里插入图片描述
思路分析:首先判断该节点是否有右子树,若存在右子树则其右子树的最左孩子节点为其中序遍历的下一个节点;若不存在右子树则判断其是否为其双亲节点的左孩子,若是则其双亲节点为其中序遍历中的下一个节点;若为其双亲节点的右孩则沿其双亲节点向上遍历,一直到找到一个为其双亲节点左孩子的节点,该节点为其中序遍历中的下一个节点。
完整代码如下:

#include <stdio.h>

struct BinaryTreeNode{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
BinaryTreeNode* m_pParent;
};
/*创建已知的二叉树,并测试*/
BinaryTreeNode* Next(BinaryTreeNode* p);

BinaryTreeNode* createTreeNode(int value){
BinaryTreeNode* Node=new BinaryTreeNode();
Node->m_nValue=value;
Node->m_pLeft=nullptr;
Node->m_pRight=nullptr;
Node->m_pParent=nullptr;
return Node;
}
void createTree(BinaryTreeNode* Parent,BinaryTreeNode* Left,BinaryTreeNode* Right){
if(Parent!=nullptr){
Parent->m_pLeft=Left;
Parent->m_pRight=Right;
if(Left!=nullptr)
Left->m_pParent=Parent;
if(Right!=nullptr)
Right->m_pParent=Parent;
}
}
void createAndTest(){
BinaryTreeNode* p1=createTreeNode(12);
BinaryTreeNode* p2=createTreeNode(5);
BinaryTreeNode* p3=createTreeNode(6);
BinaryTreeNode* p4=createTreeNode(4);
BinaryTreeNode* p5=createTreeNode(8);
BinaryTreeNode* p6=createTreeNode(7);
BinaryTreeNode* p7=createTreeNode(9);

createTree(p1,p2,p3);
createTree(p2,p4,p5);
createTree(p3,p6,nullptr);
createTree(p5,nullptr,p7);

printf("p2节点在中序遍历中下一个节点为:%d\n",Next(p2)->m_nValue);
printf("p5节点在中序遍历中下一个节点为:%d\n",Next(p5)->m_nValue);
printf("p7节点在中序遍历中下一个节点为:%d\n",Next(p7)->m_nValue);
}
/*查找某一节点在中序遍历中的下一个节点*/
BinaryTreeNode* Next(BinaryTreeNode* p){
if(p==nullptr)
return nullptr;
BinaryTreeNode* next=nullptr;
if(p->m_pRight!=nullptr)
{
BinaryTreeNode* Right=p->m_pRight;
while(Right->m_pLeft!=nullptr)
Right=Right->m_pLeft;
next=Right; 
}           
else        
if(p->m_pParent!=nullptr){    
BinaryTreeNode* Parent=p->m_pParent;
BinaryTreeNode* q=p;
while(Parent!=nullptr&&Parent->m_pRight==q)
{     
q=Parent;
Parent=Parent->m_pParent;
}   
next=Parent;
}
return next;
}

int main(){
createAndTest();
}              

运行结果如下:
在这里插入图片描述

此树为例:
在这里插入图片描述
树中12,5,6,4,8,7,9依次为节点p1-7

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值