TExcelTAD
Home › Data Structures: Hashing, Search Trees, B-Trees & Union-Find › The Expected Height of a Random BST

The Expected Height of a Random BST

Every BST operation costs O(h)O(h), and hh ranges from ⌊lg⁡n⌋\lfloor \lg n \rfloor for a perfectly balanced tree to n−1n - 1 for a path. Which one do we get in practice? If the keys arrive in random order, the answer is reassuring: the tree is shallow, with expected height O(lg⁡n)O(\lg n). This lesson states the result, checks it by simulation, and sketches the proof, which uses a neat trick: analyse 2h2^h instead of hh.

The result does not make plain BSTs safe. Real keys often arrive sorted or nearly sorted, and deletions destroy the randomness. That is the motivation for red-black trees, which guarantee O(lg⁡n)O(\lg n) height for every sequence of operations.

Randomly built trees

A randomly built BST on nn distinct keys is the tree obtained by inserting them, starting from an empty tree, in an order chosen uniformly at random from all n!n! orders. Two facts describe it.

  • Average depth. The average depth of a node is 2(1+1/n)Hn−4≈2ln⁡n≈1.39lg⁡n2(1 + 1/n) H_n - 4 \approx 2 \ln n \approx 1.39 \lg n, where Hn=1+12+⋯+1nH_n = 1 + \frac{1}{2} + \cdots + \frac{1}{n}. This is the same computation as the expected comparisons of randomized quicksort: inserting the keys makes exactly the comparisons quicksort makes when it always picks the first element of the subarray as pivot, and a node's depth is the number of comparisons spent on it.
  • Height. The expected height is O(lg⁡n)O(\lg n). More precisely it is cln⁡n−3c2(c−1)ln⁡ln⁡n+O(1)c \ln n - \frac{3c}{2(c - 1)} \ln \ln n + O(1) with c≈4.311c \approx 4.311 (a result of Luc Devroye and Bruce Reed), so about 2.99lg⁡n2.99 \lg n for large nn. The height is concentrated: it rarely deviates from its expectation by more than a few levels.

The program builds random trees and compares the measured average depth and height with these formulas.

python · try it yourself
import math, random

def build(keys):
    """insert keys into a BST stored in arrays; returns (sum of depths, height)"""
    left, right, key = [-1] * len(keys), [-1] * len(keys), keys
    total, height = 0, 0
    for i in range(1, len(keys)):
        x, d = 0, 0
        while True:
            d += 1
            side = left if keys[i] < key[x] else right
            if side[x] == -1:
                side[x] = i
                break
            x = side[x]
        total += d
        height = max(height, d)
    return total, height

rng = random.Random(8)
c = 4.311
print(f"{'n':>5} {'avg depth':>10} {'2(1+1/n)H_n-4':>14} {'height (mean of 10)':>20} {'c ln n - 1.953 ln ln n':>23}")
for n in [64, 256, 1024, 4096]:
    depths, heights = 0, []
    for _ in range(10):
        keys = list(range(n))
        rng.shuffle(keys)
        t, h = build(keys)
        depths += t / n
        heights.append(h)
    H = sum(1 / i for i in range(1, n + 1))
    exact = 2 * (1 + 1 / n) * H - 4
    devroye = c * math.log(n) - 3 * c / (2 * (c - 1)) * math.log(math.log(n))
    print(f"{n:>5} {depths / 10:>10.2f} {exact:>14.2f} {sum(heights) / 10:>11.1f} (range {min(heights)}-{max(heights)}) {devroye:>12.1f}")
    n  avg depth  2(1+1/n)H_n-4  height (mean of 10)  c ln n - 1.953 ln ln n
   64       5.75           5.64        10.8 (range 9-15)         15.1
  256       8.52           8.30        16.1 (range 14-19)         20.6
 1024      10.69          11.03        20.5 (range 18-24)         26.1
 4096      14.19          13.79        27.2 (range 26-29)         31.7

The average depth matches its exact formula closely. The height sits several levels below the two leading terms of the asymptotic formula, because the O(1)O(1) term is not small for these nn; what the formula does predict is the growth, about 6 levels each time nn is multiplied by 4 (2.99lg⁡4≈62.99 \lg 4 \approx 6), and the measured means grow by 5 to 7. Either way the height is far from nn: for 4096 keys it is in the twenties, while a sorted insertion order would give 4095.

Building a BST is quicksort

The claim about quicksort can be checked directly: count the key comparisons made while inserting a sequence into a BST, and the comparisons quicksort makes on the same sequence when it takes the first element as pivot and keeps the order of the elements within each part (a stable partition, as the BST does). They are equal for every input, not just on average.

python · try it yourself
import random

def bst_comparisons(keys):
    root, comps = None, 0                 # node = [key, left, right]
    for k in keys:
        if root is None:
            root = [k, None, None]; continue
        x = root
        while True:
            comps += 1
            i = 1 if k < x[0] else 2
            if x[i] is None:
                x[i] = [k, None, None]; break
            x = x[i]
    return comps

def quicksort_comparisons(a):
    if len(a) <= 1:
        return 0
    pivot, rest = a[0], a[1:]
    smaller = [x for x in rest if x < pivot]           # stable partition
    larger = [x for x in rest if x > pivot]
    return len(rest) + quicksort_comparisons(smaller) + quicksort_comparisons(larger)

rng = random.Random(3)
for trial in range(1000):
    a = rng.sample(range(100), rng.randint(0, 40))
    assert bst_comparisons(a) == quicksort_comparisons(a)
a = rng.sample(range(1000), 200)
print("1000 random sequences: BST insertion and first-pivot quicksort make equal comparisons")
print("example with 200 keys:", bst_comparisons(a), "comparisons each")
1000 random sequences: BST insertion and first-pivot quicksort make equal comparisons
example with 200 keys: 1490 comparisons each

Both make the same comparisons for the same reason: the first key becomes the root (the pivot) and is compared with every later key; the keys smaller than it then form the left subtree (the left part) in their original order, and so on recursively.

Why the height is logarithmic

The average depth being O(lg⁡n)O(\lg n) does not by itself bound the height: a tree can have small average depth and one very long path. The proof uses a different random variable.

Let XnX_n be the height of a randomly built BST on nn keys and define its exponential height Yn=2XnY_n = 2^{X_n} (with Y0=0Y_0 = 0 and Y1=1Y_1 = 1). The first key inserted becomes the root, and its rank ii among the keys is uniform on 1,…,n1, \ldots, n. The left subtree is a randomly built BST on the i−1i - 1 smaller keys and the right subtree one on the n−in - i larger keys. The height of the tree is one more than the larger of the two subtree heights, so

Yn=2max⁡(Yi−1,Yn−i)Y_n = 2 \max(Y_{i-1}, Y_{n-i})
Proof sketch: $E[X_n] \le 3 \lg n + O(1)$

Bound the maximum by the sum, max⁡(a,b)≤a+b\max(a, b) \le a + b for non-negative a,ba, b, and average over the uniform rank ii:

E[Yn]≤2n∑i=1n(E[Yi−1]+E[Yn−i])=4n∑j=0n−1E[Yj]E[Y_n] \le \frac{2}{n} \sum_{i=1}^{n} \bigl( E[Y_{i-1}] + E[Y_{n-i}] \bigr) = \frac{4}{n} \sum_{j=0}^{n-1} E[Y_j]

because each E[Yj]E[Y_j] appears twice in the sum. (The subtrees are randomly built and independent given ii, which justifies using E[Yj]E[Y_j] for them.)

Now prove by induction that E[Yn]≤14(n+33)E[Y_n] \le \frac{1}{4}\binom{n+3}{3}. It holds for n=0n = 0 and n=1n = 1 (0≤140 \le \frac14 and 1≤11 \le 1). For the step, use the identity ∑j=0n−1(j+33)=(n+34)\sum_{j=0}^{n-1} \binom{j+3}{3} = \binom{n+3}{4} (the hockey-stick identity):

E[Yn]≤4n∑j=0n−114(j+33)=1n(n+34)=14(n+33)E[Y_n] \le \frac{4}{n} \sum_{j=0}^{n-1} \frac{1}{4} \binom{j+3}{3} = \frac{1}{n} \binom{n+3}{4} = \frac{1}{4} \binom{n+3}{3}

where the last step is 1n⋅(n+3)!4! (n−1)!=14⋅(n+3)!3! n!\frac{1}{n} \cdot \frac{(n+3)!}{4!\,(n-1)!} = \frac{1}{4} \cdot \frac{(n+3)!}{3!\,n!}. So E[Yn]=O(n3)E[Y_n] = O(n^3).

Finally, 2x2^x is convex, so by Jensen's inequality 2E[Xn]≤E[2Xn]=E[Yn]≤(n+3)(n+2)(n+1)242^{E[X_n]} \le E[2^{X_n}] = E[Y_n] \le \frac{(n+3)(n+2)(n+1)}{24}. Taking logarithms, E[Xn]≤3lg⁡n+O(1)E[X_n] \le 3 \lg n + O(1).

The bound 3lg⁡n3 \lg n is loose by only a little: the true constant is c/lg⁡e≈2.99c / \lg e \approx 2.99. The trick of bounding max⁡\max by a sum works only because the exponential makes the larger term dominate anyway; applied to XnX_n directly it would give a useless linear bound. The program computes the exact expected height for small nn by trying all n!n! insertion orders, and compares it with the bound.

python · try it yourself
import math
from itertools import permutations

def height(order):
    root, h = None, 0
    for k in order:
        if root is None:
            root = [k, None, None]; continue
        x, d = root, 0
        while True:
            d += 1
            i = 1 if k < x[0] else 2
            if x[i] is None:
                x[i] = [k, None, None]; break
            x = x[i]
        h = max(h, d)
    return h

for n in range(1, 9):
    hs = [height(p) for p in permutations(range(n))]
    ey = sum(2 ** h for h in hs) / len(hs)
    print(f"n = {n}: E[height] = {sum(hs) / len(hs):.3f}, E[2^height] = {ey:7.3f} <= C(n+3,3)/4 = {math.comb(n + 3, 3) / 4:6.2f}, "
          f"bound on E[height] {math.log2(math.comb(n + 3, 3) / 4):.2f}")
n = 1: E[height] = 0.000, E[2^height] =   1.000 <= C(n+3,3)/4 =   1.00, bound on E[height] 0.00
n = 2: E[height] = 1.000, E[2^height] =   2.000 <= C(n+3,3)/4 =   2.50, bound on E[height] 1.32
n = 3: E[height] = 1.667, E[2^height] =   3.333 <= C(n+3,3)/4 =   5.00, bound on E[height] 2.32
n = 4: E[height] = 2.333, E[2^height] =   5.333 <= C(n+3,3)/4 =   8.75, bound on E[height] 3.13
n = 5: E[height] = 2.800, E[2^height] =   7.733 <= C(n+3,3)/4 =  14.00, bound on E[height] 3.81
n = 6: E[height] = 3.267, E[2^height] =  10.933 <= C(n+3,3)/4 =  21.00, bound on E[height] 4.39
n = 7: E[height] = 3.670, E[2^height] =  14.794 <= C(n+3,3)/4 =  30.00, bound on E[height] 4.91
n = 8: E[height] = 4.017, E[2^height] =  19.397 <= C(n+3,3)/4 =  41.25, bound on E[height] 5.37

Test yourself

What is the expected height of a BST built by inserting nn distinct keys in random order?

  1. Θ(1)\Theta(1)
  2. Θ(lg⁡n)\Theta(\lg n), about 2.99lg⁡n2.99 \lg n for large nn
  3. Θ(n)\Theta(\sqrt{n})
  4. Θ(n)\Theta(n)

Why does the proof analyse Yn=2XnY_n = 2^{X_n} instead of the height XnX_n itself?

  1. Because heights are always powers of 2
  2. Because max⁡(a,b)≤a+b\max(a, b) \le a + b is a tight bound when one term dominates, which the exponential ensures; for XnX_n it would give only a linear bound
  3. Because YnY_n is easier to simulate
  4. Because Jensen's inequality only works for YnY_n

The comparisons made while inserting a sequence into a BST equal the comparisons of...

  1. merge sort on the same sequence
  2. quicksort that takes the first element as pivot and partitions stably
  3. insertion sort
  4. heapsort