传送门
nowcoder
题目描述
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。
注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
C++ 代码 - nowcoder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
|
class Solution { public: TreeLinkNode* GetNext(TreeLinkNode* pNode) { if (pNode == nullptr) return nullptr;
if (pNode->right != nullptr) { pNode = pNode->right; while (pNode->left != nullptr) { pNode = pNode->left; } return pNode; }
while (pNode->next != nullptr) { TreeLinkNode* pRoot = pNode->next; if (pRoot->left == pNode) { return pRoot; } pNode = pNode->next; } return nullptr; } };
|