说的可能不直观,我们用3张图来来直观的解释一下上述三种情况,因为我觉得一张简单的图远比长篇大论要简洁易懂,所以我的笔记里有很多图,可能画的不好!
#include <iostream>
using namespace std;
struct BinaryTree
{
int data;
BinaryTree *pLeft;
BinaryTree *pRight;
BinaryTree *pParent;
};
BinaryTree *pRoot=NULL;
int arr[7]={10,6,15,4,5,12,18};
void InSertTree(BinaryTree *root1,int data)
{
//插入在左边;
if(root1->data > data)
{
if(root1->pLeft==NULL)
{
BinaryTree *node=new BinaryTree;
node->data=data;
node->pLeft=node->pRight=NULL;
node->pParent=root1;
root1->pLeft=node;
}
else
{
InSertTree(root1->pLeft,data);
}
}
//插入在右边;
else
{
if(root1->pRight==NULL)
{
BinaryTree *node=new BinaryTree;
node->data=data;
node->pLeft=node->pRight=NULL;
node->pParent=root1;
root1->pRight=node;
}
else
{
InSertTree(root1->pRight,data);
}
}
}
void CreateTree(BinaryTree **root,int length,int *array)
{
for(int i=0;i<length;i++)
{
if(*root==NULL)
{
BinaryTree *pNode=new BinaryTree;
pNode->data=array[i];
pNode->pLeft=pNode->pRight=NULL;
*root=pNode;
}
else
InSertTree(*root,array[i]);
}
}
BinaryTree *GetNextNode(BinaryTree* pNode)
{
if(pNode==NULL)
return NULL;
BinaryTree *pNext=NULL;
if(pNode->pRight!=NULL)
{
BinaryTree *right=pNode->pRight;
while(right->pLeft!=NULL)
right=right->pLeft;//找到最左边的一个节点;
pNext=right;
}
else if(pNode->pParent!=NULL)
{
BinaryTree *pCurrent=pNode;
BinaryTree *parent=pNode->pParent;
while(parent!=NULL && pCurrent==parent->pRight)
{
pCurrent=parent;
parent=parent->pParent;
}
pNext=parent;
}
return pNext;
}
int main()
{
BinaryTree *result=NULL;
CreateTree(&pRoot,7,arr);
result=GetNextNode(pRoot);
if(NULL==result)
cout<<"输入的结点不存在!"<<endl;
else
cout<<pRoot->data<<"的下一个结点为:"<<result->data<<endl;
system("pause");
return 0;
}
输入的二叉树是:
运行结果:
原文:http://blog.csdn.net/gogokongyin/article/details/51778339