Inorder Successor in BST

Pattern: Floor and ceil

medium

The successor of p is the smallest value larger than p. Walk down from the root: when a node is larger than p, it is a candidate and a smaller candidate could be on its left; otherwise the successor must be on the right.

The problem

Given a BST and one of its nodes p, return the node with the smallest value greater than p.val, or null if there is none. The example gives 5 for p = 4. LeetCode's version is premium. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • What is the successor in terms of values?
  • When a node is larger than p, could something smaller still be larger than p?
  • What if p has a right subtree?

Hints

    Brute force, and why it fails

    Inorder walk, returning the node after p: O(n).

    The key insight

    The successor is the ceil of a value just above p, found on one path from the root.

    Dry run

    best5

    BST [5, 3, 6, 2, 4, null, null, 1], p = 4. 5 > 4: candidate 5, go left.

    Step 1 of 3

    The plan

    best = null; n = root
    while n: if n.val > p.val: best = n; n = n.left  else: n = n.right
    return best
    

    Complexity

    Time
    O(h)
    Space
    O(1)

    One path down.

    Edge cases

    • p is the maximum: null.
    • p has a right subtree.
    • p is a leaf on a left branch.
    I've built my logic, show the code

    Java

    class Solution {
        public TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
            TreeNode best = null;
            for (TreeNode n = root; n != null; ) {
                if (n.val > p.val) { best = n; n = n.left; }   // bigger than p: a candidate; try for a smaller one
                else n = n.right;                              // not bigger: the successor is to the right
            }
            return best;
        }
    }

    C++

    class Solution {
    public:
        TreeNode* inorderSuccessor(TreeNode* root, TreeNode* p) {
            TreeNode* best = NULL;
            for (TreeNode* n = root; n != NULL; ) {
                if (n->val > p->val) { best = n; n = n->left; }   // bigger than p: a candidate; try for a smaller one
                else n = n->right;                                // not bigger: the successor is to the right
            }
            return best;
        }
    };

    Python

    class Solution:
        def inorderSuccessor(self, root, p):
            best, n = None, root
            while n:
                if n.val > p.val:
                    best, n = n, n.left             # bigger than p: a candidate; try for a smaller one
                else:
                    n = n.right                     # not bigger: the successor is to the right
            return best

    Common mistakes

    • Returning p's right child without going to its far left.
    • Using >= and returning p itself.

    Similar problems