题目链接:https://www.acwing.com/problem/content/description/31/
题目如下:
中序遍历示例:(左根右)
中序遍历结果为:A C BD F H E MG
/**
* 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;
}
};