First, we use recursive way.
Successor
1 public class Solution { 2 public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { 3 if (root == null) { 4 return null; 5 } 6 if (root.val <= p.val) { 7 return inorderSuccessor(root.right, p); 8 } else { 9 TreeNode left = inorderSuccessor(root.left, p); 10 return left == null ? root : left; 11 } 12 } 13 }
Predecessor
1 public class Solution { 2 public TreeNode inorderSuccessor(TreeNode root, TreeNode p) { 3 if (root == null) { 4 return null; 5 } 6 if (root.val >= p.val) { 7 return inorderSuccessor(root.left, p); 8 } else { 9 TreeNode right = inorderSuccessor(root.right, p); 10 return right == null ? root : right; 11 } 12 } 13 }