主要思想分为两步:
- 如果有右子树,则为右子树的最左侧
- 如果没有右子树,则一直往父亲节点上找,直到当前节点不是父亲节点的右子树为止。
/**
* 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;
}
};