您的位置:首页 > 其它

寻找二叉搜索树的后继节点

2013-09-16 16:11 183 查看
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
typedef struct _tree_node
{
int m_nValue;
struct _tree_node *m_pParent;
struct _tree_node *m_pLeft;
struct _tree_node *m_pRight;
}TreeNode;

void initTree(TreeNode **ppHead,int value,TreeNode *pNodeParent)
{
if(*ppHead==NULL)
{
*ppHead=(TreeNode *)malloc(sizeof(TreeNode));
assert(*ppHead!=NULL);
(*ppHead)->m_nValue=value;
(*ppHead)->m_pParent=pNodeParent;
(*ppHead)->m_pLeft=NULL;
(*ppHead)->m_pRight=NULL;
}
else if(value<(*ppHead)->m_nValue)
{
initTree(&(*ppHead)->m_pLeft,value,*ppHead);
}
else
{
initTree(&(*ppHead)->m_pRight,value,*ppHead);
}
}

/*void printTree(TreeNode *pNode)
{
if(pNode==NULL)
return;
printTree(pNode->m_pLeft);
printf("%d",pNode->m_nValue);
printTree(pNode->m_pRight);
}*/

TreeNode *minNode(TreeNode *pHead)
{
if(pHead==NULL)
return NULL;

while(pHead->m_pLeft)
{
pHead=pHead->m_pLeft;
}

return pHead;
}

TreeNode *successor(TreeNode *pNode)
{
if(pNode==NULL)
return NULL;
if(pNode->m_pRight)
return minNode(pNode->m_pRight);
TreeNode *pNext=pNode->m_pParent;
while(pNext&&pNext->m_pRight==pNode)
{
pNode=pNext;
pNext=pNode->m_pParent;
}

return pNext;
}

TreeNode *findNode(TreeNode *pHead,int value)
{
if(pHead==NULL)
return NULL;
if(pHead->m_nValue==value)
return pHead;
else if(value<pHead->m_nValue)
return findNode(pHead->m_pLeft,value);
else
return findNode(pHead->m_pRight,value);
}

int main()
{
TreeNode *pHead=NULL;
TreeNode *pNodeParent=NULL;
int value;
while(scanf("%d",&value)&&value!=-1)
{
initTree(&pHead,value,pNodeParent);
}

// printTree(pHead);

TreeNode *pNode=findNode(pHead,6);

TreeNode *pNext=successor(pNode);
if(pNext!=NULL)
printf("%d ",pNext->m_nValue);
else
printf("no number");

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: