Trees & BST · Pattern 12 of 12

Floor, ceil, successor and predecessor in a BST

Walk one path from the root. Every time you move away from a node that could be the answer, remember it as the best candidate so far.

3 variations · 4 problems · 5 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • The closest value at or below (floor) or at or above (ceil) x
  • The next or previous value in sorted order
  • A pair of values in a BST with a given sum

The template

Miscellaneous BST Questions
// floor: the largest value <= x, or -1
int floorBST(TreeNode root, int x) {
    int res = -1;
    while (root != null) {
        if (root.val == x) return x;
        if (root.val < x) { res = root.val; root = root.right; }   // a candidate; try bigger
        else root = root.left;
    }
    return res;
}

// ceil: the smallest value >= x, or -1
int ceilBST(TreeNode root, int x) {
    int res = -1;
    while (root != null) {
        if (root.val == x) return x;
        if (root.val > x) { res = root.val; root = root.left; }    // a candidate; try smaller
        else root = root.right;
    }
    return res;
}

// inorder successor: the smallest value greater than p's
TreeNode inorderSuccessor(TreeNode root, TreeNode p) {
    TreeNode res = null;
    while (root != null) {
        if (root.val > p.val) { res = root; root = root.left; }
        else root = root.right;
    }
    return res;
}

The variations

  1. 1Floor and ceil

    For the floor, a node smaller than x is a candidate: save it and go right to look for a bigger one. Ceil is the mirror image.

    Now you solve
  2. 2Inorder successor

    The successor is the ceil of p.val + 1: every node bigger than p is a candidate, so save it and go left. The predecessor is the mirror image.

  3. 3Use the sorted order

    Inorder is a sorted array, so two pointers find a pair with a sum. Run an inorder iterator from the left and a reverse one from the right, or keep a set of values seen.

Mistakes to avoid

  • Successor: going to the leftmost node of p's right subtree only works when p has a right child. Walking from the root with a candidate handles both cases.
  • Floor and ceil: returning the last node visited instead of the last candidate saved.
  • Two Sum in a BST: a hash set works on any tree; the two-iterator version (smallest and largest) uses the BST order and O(h) space.
Back to Trees & BST →

Mark it done once you can write the template from memory and you have solved the worked examples yourself.