AcWing 19. 二叉树的下一个节点
原题链接
中等
作者:
syadream
,
2022-07-12 12:01:26
,
所有人可见
,
阅读 248
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode *father;
* TreeNode(int x) : val(x), left(NULL), right(NULL), father(NULL) {}
* };
*/
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* p) {
// prediection of 2023 examination
// in this case, each node stores its parents' information
// # if the node has right child, the leftmost node of the right subtree is the answer
if (p->right) {
p = p->right;
while (p->left) p = p->left;
return p;
}
// if the node has the parent node and it’s the right node of the parent node, it need change to its parent to find the next.
// p->father 是边界条件, 当结点p为根节点且没有左右儿子时应该返回null
while (p->father &&p == p->father->right) p = p->father;
return p->father;
}
};