The main idea is divided into two steps:
- If there is a right subtree, the leftmost of the right subtree
- If there is no right subtree, it keeps looking for the parent node until the current node is not the right subtree of the parent node.
/**
* 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) {
if (p->right) {
p = p->right;
while (p->left) p = p->left;
return p;
}
while (p->father && p == p->father->right) p = p->father;
return p->father;
}
};