The Expected Height of a Random BST
Every BST operation costs , and ranges from for a perfectly balanced tree to 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 . This lesson states the result, checks it by simulation, and sketches the proof, which uses a neat trick: analyse instead of .
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 height for every sequence of operations.
Randomly built trees
A randomly built BST on distinct keys is the tree obtained by inserting them, starting from an empty tree, in an order chosen uniformly at random from all orders. Two facts describe it.
- Average depth. The average depth of a node is , where . 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 . More precisely it is with (a result of Luc Devroye and Bruce Reed), so about for large . 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.
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 term is not small for these ; what the formula does predict is the growth, about 6 levels each time is multiplied by 4 (), and the measured means grow by 5 to 7. Either way the height is far from : 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.
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 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 be the height of a randomly built BST on keys and define its exponential height (with and ). The first key inserted becomes the root, and its rank among the keys is uniform on . The left subtree is a randomly built BST on the smaller keys and the right subtree one on the larger keys. The height of the tree is one more than the larger of the two subtree heights, so
Proof sketch: $E[X_n] \le 3 \lg n + O(1)$
Bound the maximum by the sum, for non-negative , and average over the uniform rank :
because each appears twice in the sum. (The subtrees are randomly built and independent given , which justifies using for them.)
Now prove by induction that . It holds for and ( and ). For the step, use the identity (the hockey-stick identity):
where the last step is . So .
Finally, is convex, so by Jensen's inequality . Taking logarithms, .
The bound is loose by only a little: the true constant is . The trick of bounding by a sum works only because the exponential makes the larger term dominate anyway; applied to directly it would give a useless linear bound. The program computes the exact expected height for small by trying all insertion orders, and compares it with the bound.
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 distinct keys in random order?
- , about for large
Why does the proof analyse instead of the height itself?
- Because heights are always powers of 2
- Because is a tight bound when one term dominates, which the exponential ensures; for it would give only a linear bound
- Because is easier to simulate
- Because Jensen's inequality only works for
The comparisons made while inserting a sequence into a BST equal the comparisons of...
- merge sort on the same sequence
- quicksort that takes the first element as pivot and partitions stably
- insertion sort
- heapsort