Skip to content

Instantly share code, notes, and snippets.

@necusjz
Last active April 25, 2019 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save necusjz/f19bd0f21ea220560a39f7739373c1fb to your computer and use it in GitHub Desktop.
Save necusjz/f19bd0f21ea220560a39f7739373c1fb to your computer and use it in GitHub Desktop.
面试题 8:二叉树的下一个节点
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment