First, we use recursive way.
Successor
public class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if (root == null) {
return null;
}
if (root.val <= p.val) {
return inorderSuccessor(root.right, p);
} else {
TreeNode left = inorderSuccessor(root.left, p);
return left == null ? root : left;
}
}
}
Predecessor
public class Solution {
public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
if (root == null) {
return null;
}
if (root.val >= p.val) {
return inorderSuccessor(root.left, p);
} else {
TreeNode right = inorderSuccessor(root.right, p);
return right == null ? root : right;
}
}
}