285. 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.

Note: If the given node has no in-order successor in the tree, returnnull.


Seen this question in a real interview before?

Yes

No

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
        TreeNode pre = null;

        while (root != null){
            if (root.val == p.val){
                if (root.right != null) return findLeftMost(root.right);
                return pre;
            }
            else{
                if (p.val < root.val){
                    pre = root;
                    root = root.left;
                }
                else{
                    root = root.right;
                }
            }
        }

        return null;
    }

    private TreeNode findLeftMost(TreeNode root){
        while (root.left != null){
            root = root.left;
        }

        return root;
    }
}

results for ""

    No results matching ""