思路:如果遇到比目标大的就记录下来作为潜在的successor,如果不是就直接跳过
//Iteration
class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
TreeNode succesor = null;
if (root == null || p == null){
return succesor;
}
while(root != null){
if (root.val > p.val){
succesor = root;
root = root.left;
} else {
root = root.right;
}
}
return succesor;
}
}
//Recursion
class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p){
if (root == null){
return null;
}
if(root.val > p.val){
TreeNode temp = inorderSuccessor(root.left, p);
return temp = temp == null ? root : temp;
} else {
return inorderSuccessor(root.right,p);
}
}
}