Simple Algorithm
Algorithms & Data Structures · Optimized · 22 min

Binary Search Trees

Ordered keys, O(height) operations, and why height is everything.

A sorted array finds any of a million keys in 20 comparisons, but inserting one new key can shift a million others. A binary search tree keeps the 20-comparison search and makes insertion cheap too, as long as the tree stays short. Feed it the same million keys in sorted order, though, and every search becomes a walk down a million-node chain.

What you’ll learn

  • State the binary-search-tree property and use it to search, find the minimum and maximum, and insert in O(h)O(h) time, where hh is the height.
  • Find successors, predecessors, floors and ceilings, and delete a key in all three cases, proving that the BST property survives.
  • Explain why the height decides everything: hh ranges from ⌊log⁡2n⌋\lfloor\log_2 n\rfloor to n−1n-1, and random insertion orders give average depth 2(1+1/n)Hn−4≈1.39log⁡2n2(1+1/n)H_n-4\approx1.39\log_2 n.
  • Recognize ordered-set problems (successor, floor, ceiling, nearest value under insertions and deletions) and solve them with the library's ordered set, choosing a hash set or a heap when order is not needed.

The BST property, and search along one path

A binary search tree (BST) stores one key per node, and each node has a left and a right child, either of which may be missing. What makes it a search tree is one rule about whole subtrees, not just about children:

Searching for a key kk uses the property the way binary search uses a sorted array. Compare kk with the root: if they are equal, stop; if kk is smaller, every candidate lies in the left subtree, so go left; if larger, go right. The loop invariant is if kk is in the tree, it is in the subtree of the current node. Each comparison moves one level down, so a search makes at most h+1h+1 comparisons, where hh is the tree's height (heights count edges: a single node has height 0). The minimum sits at the end of the leftmost path, the maximum at the end of the rightmost one.

Insertion is an unsuccessful search: walk down until you fall off the tree, and hang the new key exactly where you fell off.

python
class Node:
    __slots__ = ('key', 'left', 'right')
    def __init__(self, key):
        self.key, self.left, self.right = key, None, None

def search(x, key):                    # O(h): follows one downward path
    while x is not None and key != x.key:
        x = x.left if key < x.key else x.right
    return x                           # the node holding key, or None

def insert(x, key):                    # returns the root of the updated subtree
    if x is None:
        return Node(key)
    if key < x.key:
        x.left = insert(x.left, key)
    elif key > x.key:
        x.right = insert(x.right, key)
    return x                           # an equal key is already present

Iterative search, recursive insertion. Both follow one root-to-leaf path, so both take O(h)O(h) time. Insertion returns the root of the updated subtree so that the parent's pointer can be reset, a pattern deletion reuses below.

Sorted order for free: inorder, successor, predecessor

Two consequences. First, inserting nn keys and then walking the tree sorts them (tree sort), so in the comparison model building a BST of nn keys takes Ω(nlog⁡n)\Omega(n\log n) comparisons in the worst case: no comparison-based search tree can make every insertion cost o(log⁡n)o(\log n), even amortized. Second, questions about order become walks along a path.

The successor of xx is the next key in sorted order, found in one of two places. If xx has a right subtree, it is that subtree's minimum: go right once, then left as far as possible. Otherwise it is the lowest ancestor of xx whose left subtree contains xx: climb until you arrive at a node from its left child. The predecessor is the mirror image, and both cost O(h)O(h).

Without parent pointers, a single downward walk does the job, and it works even when the query key is not stored, which turns it into a strictly higher or ceiling query:

python
def successor(root, key):              # smallest stored key > key, or None
    best, x = None, root
    while x is not None:
        if x.key > key:
            best, x = x.key, x.left    # a candidate; look for a smaller one
        else:
            x = x.right                # x and its left subtree are all <= key
    return best

The last node where the walk turned left is the answer, because every key met after it is smaller. Writing ≥\ge instead of >> gives the ceiling (the smallest key ≥k\ge k), and swapping left with right gives the predecessor and the floor.

Check your understanding

In the tree built by inserting 50, 30, 70, 20, 40, 60, 80, what is the successor of 40, and which case finds it?

  1. 60, the smallest key in 50's right subtree
  2. 50: 40 has no right subtree, so climb until you arrive at a node from its left child, which first happens at 50
  3. 30, its parent
  4. 40 has no successor, because it is a leaf
Show the answer

B. 50: 40 has no right subtree, so climb until you arrive at a node from its left child, which first happens at 50

40 is the right child of 30, and 30 is the left child of 50. Climbing from 40, the first node reached from its left child is 50, and indeed 50 comes next in sorted order: 20, 30, 40, 50, 60, 70, 80.

Deletion: three cases

To delete a key, first find its node zz. Then:

  1. zz is a leaf: remove it.
  2. zz has one child: splice zz out, and the child takes its place.
  3. zz has two children: find its successor yy, the minimum of zz's right subtree. Put yy's key in zz's place, then delete yy from the right subtree. Since yy is a minimum, it has no left child, so deleting it is case 1 or 2. This is Hibbard deletion (1962).
python
def delete(x, key):                    # returns the root of the updated subtree
    if x is None:
        return None
    if key < x.key:
        x.left = delete(x.left, key)
    elif key > x.key:
        x.right = delete(x.right, key)
    elif x.left is None:               # cases 1 and 2: at most one child
        return x.right
    elif x.right is None:
        return x.left
    else:                              # case 3: two children
        s = x.right
        while s.left is not None:      # successor = minimum of the right subtree
            s = s.left
        x.key = s.key                  # copy it up, then remove it from below
        x.right = delete(x.right, s.key)
    return x

Copying the successor's key up is the short version. Libraries move the successor's node into place instead (CLRS's TRANSPLANT), so that iterators and the data attached to each key stay valid.

DerivationWhy the BST property survives
  1. {keys below the child} ⊆ {keys below z} ⊆ (lo(z), hi(z))\{\text{keys below the child}\}\ \subseteq\ \{\text{keys below } z\}\ \subseteq\ \big(lo(z),\ hi(z)\big)

    Cases 1 and 2. Splicing out zz moves its child's subtree up one level. Every key in that subtree was already inside the interval of keys allowed below zz, so it is still on the correct side of every ancestor:

  2. max⁡L < z.key < y.key=min⁡R < min⁡(R∖{y})\max L\ <\ z.key\ <\ y.key=\min R\ <\ \min\big(R\setminus\{y\}\big)

    Case 3. Let LL and RR be the key sets of zz's left and right subtrees. The successor yy is the minimum of RR, so it is larger than everything in LL and smaller than everything else in RR. It can sit in zz's place:

  3. Tdelete(n)=O(h)T_{\text{delete}}(n)=O(h)

    The successor has no left child. A left child of yy would be a key of RR smaller than yy, contradicting y=min⁡Ry=\min R. So removing yy is case 1 or 2, and the whole deletion walks at most two downward paths:

Height is everything

Search, minimum, maximum, successor, predecessor, insertion and deletion all walk down (and possibly back up) one path, so every operation costs O(h)O(h). For nn keys the height can be anything from ⌊log⁡2n⌋\lfloor\log_2 n\rfloor, for a complete tree, to n−1n-1, for a path, and the insertion order alone decides which.

Think first Build that path with n=1000n=1000 keys inserted in increasing order. How many key comparisons does the construction make in total?

Key ii lands at depth i−1i-1 after being compared with all i−1i-1 earlier keys, so the total is 0+1+⋯+999=(10002)=499,5000+1+\cdots+999=\binom{1000}{2}=499{,}500: Θ(n2)\Theta(n^2). That is exactly the comparison count of quicksort with a first-element pivot on sorted input, and the coincidence is no accident.

Now insert the keys in a uniformly random order. The first key becomes the root and splits the others into those that go left and those that go right, and each side is again built in random order: this is quicksort with the first element as the pivot. When a key is inserted it is compared with each of its ancestors, which are exactly the pivots of the ranges that contained it. So the total number of comparisons, the sum of all depths, equals quicksort's comparison count.

DerivationAverage depth of a random BST
  1. Pr⁡[ i is an ancestor of j ]=1∣i−j∣+1\Pr[\,i\text{ is an ancestor of }j\,]=\frac{1}{|i-j|+1}

    Label the keys 1,…,n1,\dots,n by rank. Key ii becomes an ancestor of key jj exactly when ii is inserted first among the keys between them, inclusive: until then all of them follow the same search path, and the first one to arrive separates the rest. Each of the ∣i−j∣+1|i-j|+1 keys is equally likely to be first:

  2. E[∑jdepth⁡(j)]=∑d=1n−12(n−d)d+1=2(n+1)Hn−4n\E\Big[\sum_{j}\operatorname{depth}(j)\Big]=\sum_{d=1}^{n-1}\frac{2(n-d)}{d+1}=2(n+1)H_n-4n

    Sum over ordered pairs, grouping them by the distance d=∣i−j∣d=|i-j|, which occurs for 2(n−d)2(n-d) ordered pairs:

  3. depth⁡‾=2(1+1n)Hn−4 ≈ 2ln⁡n ≈ 1.39log⁡2n\overline{\operatorname{depth}}=2\Big(1+\frac1n\Big)H_n-4\ \approx\ 2\ln n\ \approx\ 1.39\log_2 n

    Divide by nn, using Hn=1+12+⋯+1n=ln⁡n+0.5772…+o(1)H_n=1+\tfrac12+\cdots+\tfrac1n=\ln n+0.5772\ldots+o(1):

Predict before you look

A random BST holds n=1000n=1000 keys. What is the expected average depth of a key? (A complete tree with 1000 keys averages about 8.0.)

Show the answer

11

H1000≈7.4855H_{1000}\approx7.4855, so 2(1.001)(7.4855)−4≈10.992(1.001)(7.4855)-4\approx10.99: about 38% deeper than the complete tree's 7.99, and nowhere near the 499.5 of the sorted-input path. In simulations the height of such trees is typically around 20: the deepest key sits about twice as deep as an average one.

Recognizing it

A search tree, in practice your library's balanced one, is the tool when a problem needs order and change at the same time:

  • "the smallest value greater than xx", "the closest value to xx", floor and ceiling, predecessor and successor;
  • insertions and deletions interleaved with those questions, online, with nn and qq around 10510^5 to 10610^6, so that O(log⁡n)O(\log n) per operation fits and O(n)O(n) does not;
  • intervals that must not overlap, or events kept in time order while some are cancelled;
  • "the kk-th smallest" or "how many are below xx" under updates, which needs an augmented tree.
Problem (in brief)Key ideaCost
Accept a booking [s,e)[s,e) only if it overlaps no accepted bookingOrdered map keyed by start: check the predecessor's end and the successor's startO(log⁡n)O(\log n) per booking
Is there i≠ji\ne j with ∣i−j∣≤k\abs{i-j}\le k and ∣a[i]−a[j]∣≤t\abs{a[i]-a[j]}\le t?Sliding window of kk values in an ordered set; one ceiling query per elementO(nlog⁡k)O(n\log k)
For each element, the closest value among the earlier onesInsert as you go; compare the floor and the ceilingO(nlog⁡n)O(n\log n)
The kk-th smallest key of a given BSTInorder walk that stops after kk keysO(h+k)O(h+k)
For each element, how many smaller ones lie to its rightOrder statistics (an augmented tree), or a Fenwick tree over compressed valuesO(nlog⁡n)O(n\log n)
Five common shapes of an ordered-set problem.
cpp
#include <set>
#include <vector>
using namespace std;

// Is there i < j with j - i <= k and |a[i] - a[j]| <= t ?
bool nearbyAlmostDuplicate(const vector<long long>& a, int k, long long t) {
    set<long long> window;                        // values of the last k elements
    for (int j = 0; j < (int)a.size(); ++j) {
        auto it = window.lower_bound(a[j] - t);   // ceiling of a[j] - t: O(log k)
        if (it != window.end() && *it <= a[j] + t) return true;
        window.insert(a[j]);
        if (j >= k) window.erase(a[j - k]);       // slide: keep indices j-k+1 .. j
    }
    return false;
}

The contest idiom: lower_bound(x) is the ceiling, the smallest element ≥x\ge x. A plain set suffices here because a duplicate value inside the window is reported before it could be inserted twice. The values are 64-bit, so a[j]±ta[j]\pm t cannot overflow for 32-bit inputs.

LanguageCeiling (smallest ≥x\ge x)Floor (largest ≤x\le x)Notes
C++ std::set, std::maps.lower_bound(x)prev(s.upper_bound(x)), unless it is begin()Red-black trees in libstdc++, libc++ and MSVC; multiset for duplicates
Java TreeSet, TreeMapceiling(x), ceilingKey(x)floor(x), floorKey(x)Red-black trees; higher and lower are the strict versions
Pythonbisect_left on a sorted listbisect_right minus 1No built-in ordered set: insertion into a list is O(n)O(n). The third-party sortedcontainers keeps a list of sorted sublists, not a tree
Every ordered set answers these in O(log⁡n)O(\log n). Each library returns "no answer" its own way: end(), null, or an index equal to the length.
Check your understanding

You must process 2⋅1052\cdot10^5 operations in any order: insert a price, delete a price, and report the smallest stored price ≥x\ge x. Which structure fits?

  1. A hash set
  2. A binary heap
  3. A balanced BST, such as std::set
  4. A sorted array with binary search
Show the answer

C. A balanced BST, such as std::set

Ceiling queries need order, and the set changes between queries, so you need an ordered set with O(log⁡n)O(\log n) insertion, deletion and ceiling: about 2⋅105⋅18≈4⋅1062\cdot10^5\cdot18\approx4\cdot10^6 steps in all.

Key takeaways

  • The BST property is about whole subtrees: smaller keys to the left, larger to the right. Inorder traversal therefore lists the keys in sorted order.
  • Search, minimum, maximum, successor, predecessor, floor, ceiling, insertion and deletion each follow one root-to-leaf path: O(h)O(h) time.
  • Deleting a node with two children moves in its successor, which has no left child, so every deletion reduces to splicing out a node with at most one child.
  • The height ranges from ⌊log⁡2n⌋\lfloor\log_2 n\rfloor to n−1n-1. Sorted input builds a path in Θ(n2)\Theta(n^2) time; random orders give average depth 2(1+1/n)Hn−4≈1.39log⁡2n2(1+1/n)H_n-4\approx1.39\log_2 n, an average over inputs, not a guarantee.
  • Problems that mix order questions (successor, floor, ceiling, kk-th) with insertions and deletions call for the library's ordered set; membership alone calls for a hash set, and repeated minimums for a heap.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Deleting a node zz that has two children replaces it with its successor yy. Why can yy always be removed from its old position by one of the easy cases?

  1. yy is always a leaf
  2. yy is the root of zz's right subtree
  3. yy has no left child, since a left child would be a smaller key in zz's right subtree
  4. The BST property forbids left children inside a right subtree
Show the answer

C. yy has no left child, since a left child would be a smaller key in zz's right subtree

yy is the minimum of zz's right subtree. A left child of yy would also lie in that subtree and be smaller than yy, a contradiction. So yy has at most a right child, and removing it is case 1 or case 2.

Question 2

You insert nn keys in increasing order into an empty plain BST, then search for each key once. What is the total cost?

  1. Θ(nlog⁡n)\Theta(n\log n), since BST operations are logarithmic
  2. Θ(n2)\Theta(n^2): the tree is a path, so each phase makes about n2/2n^2/2 comparisons
  3. Θ(n)\Theta(n): each new key is attached right next to the previous one
  4. Θ(nlog⁡n)\Theta(n\log n) expected, because the tree rebalances itself
Show the answer

B. Θ(n2)\Theta(n^2): the tree is a path, so each phase makes about n2/2n^2/2 comparisons

The ii-th key is compared with all i−1i-1 earlier keys on its way down, so the insertions make ∑i(i−1)=n(n−1)/2\sum_i (i-1)=n(n-1)/2 comparisons, and searching for key ii afterwards takes ii comparisons: Θ(n2)\Theta(n^2) in total.

Question 3

Random insertion orders give an average depth of about 1.39log⁡2n1.39\log_2 n. What does that guarantee for an application whose keys arrive as increasing timestamps?

  1. Nothing: it is an average over insertion orders, and increasing timestamps are the worst order
  2. O(log⁡n)O(\log n) expected time per operation, because the expectation covers every input
  3. O(log⁡n)O(\log n) amortized time per operation
  4. Height O(log⁡n)O(\log n) with high probability
Show the answer

A. Nothing: it is an average over insertion orders, and increasing timestamps are the worst order

An average-case bound averages over inputs. Timestamps arrive sorted, the tree becomes a path, and each operation costs Θ(n)\Theta(n). Treaps (expected time over the algorithm's own coin flips) and balanced trees (worst-case height) are the two cures.

Question 4

In the tree built from 50, 30, 70, 20, 40, 60, 80, a ceiling query asks for the smallest key ≥45\ge45. Which nodes does the downward walk visit, and what does it return?

  1. 50, 70, 60; it returns 60
  2. 50, 30, 40; it returns 40
  3. 50, 30, 40; it returns 50
  4. All seven nodes; it returns 50
Show the answer

C. 50, 30, 40; it returns 50

At 50: 50≥4550\ge45, so record 50 and go left. At 30: 30<4530<45, go right. At 40: 40<4540<45, go right, and fall off the tree. The last recorded candidate, 50, is the answer, found by visiting three nodes.

Question 5

Which task needs an ordered structure such as a balanced BST rather than a hash table?

  1. Counting the distinct words in a document
  2. Checking whether a username is already taken
  3. Grouping words that are anagrams of each other
  4. Listing the events with timestamps in [t1,t2][t_1,t_2] while events are added and cancelled
Show the answer

D. Listing the events with timestamps in [t1,t2][t_1,t_2] while events are added and cancelled

A range query needs the keys in order: find the ceiling of t1t_1, then follow successors until you pass t2t_2, O(log⁡n+k)O(\log n+k) time for kk results in a balanced tree. A hash table scatters neighboring keys and would have to scan everything.

Go deeper

Further reading

  • T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 12.
  • D. E. Knuth, The Art of Computer Programming, vol. 3: Sorting and Searching, 2nd ed. (Addison-Wesley, 1998), section 6.2.2.
  • T. N. Hibbard, "Some combinatorial properties of certain trees with applications to searching and sorting," Journal of the ACM 9(1) (1962), 13–28.
  • R. Sedgewick & K. Wayne, Algorithms, 4th ed. (Addison-Wesley, 2011), section 3.2.