Binary Search Trees

Ordered binary trees with O(h) search, insert and delete — and why the height h is everything.

Intermediate 3 min readLesson 8 of 16 Interview Q&A

A binary search tree (BST) is a binary tree with one invariant, applied at every node:

All keys in the left subtree are smaller than the node's key, and all keys in the right subtree are larger.

That single rule turns the tree into a decision structure: at each node you go left or right, discarding a whole subtree — binary search on a structure you can insert into cheaply.

20403060807050
Searching for 40: 50 → left → 30 → right → 40. Three comparisons.

Operations

Every operation walks one root-to-leaf path, so it costs O(h) where h is the height.

OperationBalanced (h ≈ log n)Degenerate (h ≈ n)
SearchO(log n)O(n)
InsertO(log n)O(n)
DeleteO(log n)O(n)
Min / maxO(log n)O(n)
Sorted iterationO(n)O(n)

Delete: three cases

  1. Leaf — just remove it.
  2. One child — splice: replace the node with its child.
  3. Two children — copy in the in-order successor (minimum of the right subtree), then delete that successor from the right subtree (it has at most one child).
class BST {
    TreeNode root;

    boolean contains(int key) {
        TreeNode n = root;
        while (n != null) {
            if (key == n.val) return true;
            n = key < n.val ? n.left : n.right;
        }
        return false;
    }

    void insert(int key) { root = insert(root, key); }
    private TreeNode insert(TreeNode n, int key) {
        if (n == null) return new TreeNode(key);
        if (key < n.val) n.left = insert(n.left, key);
        else if (key > n.val) n.right = insert(n.right, key);
        return n;                          // duplicates ignored
    }

    void delete(int key) { root = delete(root, key); }
    private TreeNode delete(TreeNode n, int key) {
        if (n == null) return null;
        if (key < n.val) n.left = delete(n.left, key);
        else if (key > n.val) n.right = delete(n.right, key);
        else {
            if (n.left == null) return n.right;      // 0 or 1 child
            if (n.right == null) return n.left;
            TreeNode s = n.right;                    // 2 children: successor
            while (s.left != null) s = s.left;
            n.val = s.val;
            n.right = delete(n.right, s.val);
        }
        return n;
    }
}

Try it

Insert, search and delete — then press Sorted insert to watch a BST degenerate into a list.

InteractiveBinary search tree playground
20304050607080
Insert, delete or search for a value. Watch the path the comparison takes.
Nodes: 7Height: 3In-order: 20 30 40 50 60 70 80

The height problem

Insert 1, 2, 3, 4, 5 in order and every node becomes a right child: height n − 1, every operation O(n). The fix is a self-balancing BST that restructures itself to keep h = O(log n) — see Balanced trees. Library ordered maps (TreeMap, C++ std::map) are all balanced.

Useful BST queries

  • Floor / ceiling — largest key ≤ x / smallest key ≥ x: walk down, remembering the best candidate.
  • Successor — if the node has a right subtree, its minimum; otherwise the nearest ancestor whose left subtree contains the node.
  • k-th smallest — in-order traversal, stop at k (or store subtree sizes for O(h)).
  • Range query [lo, hi] — in-order traversal that prunes subtrees outside the range: O(h + k).
Validate a BST
boolean isValidBST(TreeNode root) { return valid(root, Long.MIN_VALUE, Long.MAX_VALUE); }
boolean valid(TreeNode n, long lo, long hi) {
    if (n == null) return true;
    if (n.val <= lo || n.val >= hi) return false;
    return valid(n.left, lo, n.val) && valid(n.right, n.val, hi);
}
Key takeaways
  • BST invariant: left < node < right, for every node.
  • Search/insert/delete are O(h); in-order traversal yields sorted keys.
  • Without balancing, sorted inputs give h = n. Production code uses balanced trees.
Interview questions
QFind the k-th smallest element in a BST.medium

Iterative in-order traversal; decrement k on each visit and return when it hits 0. O(h + k). If asked repeatedly with updates, store subtree sizes in each node and descend in O(h).

QConvert a sorted array to a height-balanced BST.easy

Pick the middle element as the root, recursively build the left half and the right half as its subtrees. O(n).

QLCA in a BST?easy

Walk from the root: if both values are smaller, go left; if both are larger, go right; otherwise the current node is the split point and the LCA. O(h).