题目:给定一棵二叉树和其中的一个节点,如何找出中序遍历序列的下一个节点?树中的节点除了有两个分别指向左右子节点的指针,还有一个指向父节点的指针。
BinaryTreeNode* GetNext(BinaryTreeNode* pNode)
{
if(pNode==nullptr)
return nullptr;
BinaryTreeNode* pNext=nullptr;
if(pNode->m_pRight!=nullptr)//存在右子树
{
BinaryTreeNode* pRight=pNode->m_pRight;
//下一个节点是右子树的最左节点
while(pRight->m_pLeft!=nullptr)
pRight=pRight->m_pLeft;
pNext=pRight;
}
else if(pNode->m_pParent!=nullptr)//不存在右子树
{
BinaryTreeNode* pCurrent=pNode;
BinaryTreeNode* pParent=pNode->m_pParent;
while(pParent!=nullptr&&pCurrent==pParent->m_pRight)//是父节点的右子节点
{
pCurrent=pParent;
pParent=pParent->m_pParent;
}
pNext=pParent;
}
return pNext;
}