在搜索的过程中,如果找到了p就标记一下,如果标记位为true,那么就返回这个值就行了
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
boolean flag;
TreeNode ans;
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
flag = false;
ans = null;
find(root, p);
return ans;
}
public void find(TreeNode root, TreeNode p) {
if(root == null) {
return;
}
find(root.left, p);
if(ans != null) {
return;
}
if(flag) {
ans = root;
return;
}
if(root.equals(p)) {
flag = true;
}
find(root.right, p);
}
}