二叉树的下一个节点
##题目描述
给定一个二叉树和其中一个节点,找出中序遍历序列的下一个节点
- 一个节点有右子树,下一个节点是右子树中最左的点
- 没有右子树,如果是父亲的左节点,则为父节点
- 没有右子树,是父的右节点,向上便利找到一个是它父亲点的左子节点的节点。
BinaryTreeNode *GetNext(BinaryTreeNode *pNode)
{
if(pNode == nullptr) return nullptr;
BinaryTreeNode *pNext = nullptr;
if(pNode->m_pRight)
{
BinaryTree *pRight = pNode->m_pRight;
while(pRight->m_pLeft != nullptr)
{
pRight = pRight->m_pLeft;
}
pNext = pRight;
}
else{
if(pNode->m_father->m_pLeft == pNode)
{
pNext = pNode->m_father;
}
else
{
BinaryTree *current = pNode;
BinaryTree *father = pNode->m_father;
while(father !=nullptr && father->m_pRight != current)
{
current = father;
father = father->m_father;
}
pNext = father;
}
}
return pNext;
}