Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
1 public class Solution {
2
3 public TreeNode inorderSuccessor(TreeNode root, TreeNode n) {
4 if (root == null) return null;
5
6 if (n.right != null) {
7 return min(n.right);
8 }
9
10 TreeNode succ = null;
11 while (root != null) {
12 if (n.val < root.val) { //左子树的successor都是当前树的root。
13 succ = root;
14 root = root.left;
15 } else if (n.val > root.val)
16 root = root.right;
17 else
18 break;
19 }
20 return succ;
21 }
22
23 public TreeNode min(TreeNode n) {
24 if (n.left != null) {
25 return min(n.left);
26 }
27 return n;
28 }
29 }
30
31 class TreeNode {
32 TreeNode left;
33 TreeNode right;
34 int val;
35
36 public TreeNode(int i) {
37 val = i;
38 }
39 }
Another solution
1 class Solution {
2 public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
3 return helper(root, p, null);
4 }
5
6 private TreeNode helper(TreeNode root, TreeNode p, TreeNode parent) {
7 if (root == null) {
8 return parent;
9 }
10
11 if (root.val > p.val) {
12 return helper(root.left, p, root);
13 } else {
14 return helper(root.right, p, parent);
15 }
16 }
17 }