Pages

Tuesday 18 July 2017

[Leetcode] Inorder Successor in BST

Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
Solution :


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
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) ? left : root;
  }
}
}

No comments:

Post a Comment