题目链接:https://leetcode-cn.com/problems/successor-lcci/
题目如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
dfs(root,p);
return res;
}
void dfs(TreeNode* root,TreeNode* p){
if(!root) return;
dfs(root->left,p);
if(found_p) {res=root;found_p=false;return;}//found_p不重新置为false,递归时,res会被覆盖
if(root==p) found_p=true;
dfs(root->right,p);
}
private:
bool found_p=false;
TreeNode* res=nullptr;
};