Binary Search Trees in Lean Check a result Declarations Bibliography Lean source

Chapter 22Random search trees

The third way to keep a tree shallow is to leave its shape to chance. Several classical structures do this, and all of them draw from the same distribution: the random BST. This chapter presents that distribution once, through treaps, and the structures as different ways to sample it and keep it under updates.

In a random binary search tree, key xx has expected depth Hx+1+Hn−x−2≤2ln⁡nH_{x+1} + H_{n-x} - 2 \le 2\ln n

Insert the keys 0,…,n−10, \dots, n - 1 into an empty binary search tree, without rebalancing, in a uniformly random order. Then key xx has expected depth exactly Hx+1+Hn−x−2H_{x+1} + H_{n-x} - 2, where Hk=1+12+⋯+1kH_k = 1 + \frac12 + \dots + \frac1k is the harmonic number, and this is at most 2ln⁡n2 \ln n. The tree built from an insertion order is the treap whose priorities are the positions in the order.

In Lean, insertion is Random.insertKeys, the expectation over random orders is Random.average of Chapter 32 with uniform weights, and harmonic is Mathlib’s.

The Lean statements
theoremClassical.Random.Results.random_bst_depthpropext · Classical.choice · Quot.soundClassical/Random/Abstract.lean:37
/-- **Random binary search trees.** Inserting the keys in a uniformly randomorder, key `x` has expected depth `H(x + 1) + H(n - x) - 2`… -/theorem random_bst_depth (n x : Nat) (hx : x < n) :    Treap.Random.average (fun _ => 1) (Finset.range n) (fun xs => ((insertKeys xs).erase.depth x : ℝ)) =      ((harmonic (x + 1) : ℚ) : ℝ) + ((harmonic (n - x) : ℚ) : ℝ) - 2 := …  Random.random_bst_depth n x hx
theoremClassical.Random.Results.random_bst_depth_lepropext · Classical.choice · Quot.soundClassical/Random/Abstract.lean:44
/-- …at most `2 ln n`. -/theorem random_bst_depth_le (n x : Nat) (hx : x < n) :    Treap.Random.average (fun _ => 1) (Finset.range n) (fun xs => ((insertKeys xs).erase.depth x : ℝ)) ≤      2 * Real.log n := …  Random.random_bst_depth_le n x hx
theoremClassical.Random.Results.insertKeys_treappropext · Classical.choice · Quot.soundClassical/Random/Abstract.lean:30
/-- **Insertion builds the treap of the insertion order**: inserting apermutation of the `n` keys without rebalancing gives the tree with the heapproperty for the positions in the order. -/theorem insertKeys_treap (n : Nat) (order : List Nat) (h : order.Perm (List.range n)) :    (insertKeys order).erase.size = n ∧ Geometric.Heap order.idxOf (insertKeys order).erase 0 := …  Random.insertKeys_treap n order h
9 definitions in 3 chapters · reading list

22.1 One distribution

Give the nn keys a uniformly random order, and read it as priorities: the first key in the order has the smallest priority. The treap for these priorities is the BST in which every node has a smaller priority than its descendants, Geometric.Heap of Chapter 32. It is unique. It is also the tree obtained by inserting the keys into an empty BST, without rebalancing, in that order: the first key becomes the root, and each later key is a descendant of every earlier key on its search path. This is the random BST of Hibbard (1962).

defClassical.Random.insertKeyno axiomsClassical/Random/Definitions/Abstract.lean:11
/-- Insert key `y` as a new leaf, going left at larger keys and right otherwise. -/def insertKey : LabelledTree Nat → Nat → LabelledTree Nat  | .nil, y => .node .nil y .nil  | .node l x r, y => if y < x then .node (insertKey l y) x r else .node l x (insertKey r y)
defClassical.Random.insertKeysno axiomsClassical/Random/Definitions/Abstract.lean:16
/-- Insert the keys of `order` one after the other, starting from the empty tree. -/def insertKeys (order : List Nat) : LabelledTree Nat := order.foldl insertKey .nil

Here keys are labels, compared on insertion, and the shape of the result is its erase. insertKey goes left at a larger label and right otherwise.

Theorem (insertion builds the treap). If order lists the keys 0,…,n−10, \dots, n - 1 once each, then inserting them in that order gives a tree on nn keys with the heap property for the positions in the order.

theoremClassical.Random.Results.insertKeys_treappropext · Classical.choice · Quot.soundClassical/Random/Abstract.lean:30
/-- **Insertion builds the treap of the insertion order**: inserting apermutation of the `n` keys without rebalancing gives the tree with the heapproperty for the positions in the order. -/theorem insertKeys_treap (n : Nat) (order : List Nat) (h : order.Perm (List.range n)) :    (insertKeys order).erase.size = n ∧ Geometric.Heap order.idxOf (insertKeys order).erase 0 :=  Random.insertKeys_treap n order h

Everything about the expected shape follows from one fact. A key aa is an ancestor of xx exactly when aa has the smallest priority among the keys between aa and xx, inclusive. With a uniform order this happens with probability 1/(∣a−x∣+1)1/(|a - x| + 1). The library proves the weighted version of this fact, for the random treaps of Chapter 32, in which the order is drawn with probabilities proportional to given weights; with equal weights, it is the uniform case. Summing over aa gives the expected depth of xx, its number of proper ancestors. Counting keys from 00,

E[depth(x)]  =  ∑a≠x1∣a−x∣+1  =  Hx+1+Hn−x−2  ≤  2ln⁡n.\mathbb{E}[\mathrm{depth}(x)] \;=\; \sum_{a \ne x} \frac{1}{|a - x| + 1} \;=\; H_{x+1} + H_{n-x} - 2 \;\le\; 2 \ln n .

Theorem (expected depth in a random treap). For every family of trees T xs on nn keys, one for every list xs, with the heap property for the positions in xs, the expected depth of xx over a uniformly random order is Hx+1+Hn−x−2H_{x+1} + H_{n-x} - 2, and at most 2ln⁡n2 \ln n.

theoremClassical.Random.Results.expected_depthpropext · Classical.choice · Quot.soundClassical/Random/Abstract.lean:16
/-- **Expected depth in a random treap**: `H(x + 1) + H(n - x) - 2`. -/theorem expected_depth (n x : Nat) (hx : x < n) (T : List Nat → Tree)    (spec : ∀ xs, (T xs).size = n ∧ Geometric.Heap xs.idxOf (T xs) 0) :    Treap.Random.average (fun _ => 1) (Finset.range n) (fun xs => ((T xs).depth x : ℝ)) =      ((harmonic (x + 1) : ℚ) : ℝ) + ((harmonic (n - x) : ℚ) : ℝ) - 2 :=  Random.expected_depth n x hx T spec
theoremClassical.Random.Results.expected_depth_lepropext · Classical.choice · Quot.soundClassical/Random/Abstract.lean:23
/-- In particular every expected depth is at most `2 ln n`. -/theorem expected_depth_le (n x : Nat) (hx : x < n) (T : List Nat → Tree)    (spec : ∀ xs, (T xs).size = n ∧ Geometric.Heap xs.idxOf (T xs) 0) :    Treap.Random.average (fun _ => 1) (Finset.range n) (fun xs => ((T xs).depth x : ℝ)) ≤      2 * Real.log n :=  Random.expected_depth_le n x hx T spec

Combining the two theorems gives the headline result for random insertion orders:

theoremClassical.Random.Results.random_bst_depthpropext · Classical.choice · Quot.soundClassical/Random/Abstract.lean:37
/-- **Random binary search trees.** Inserting the keys in a uniformly randomorder, key `x` has expected depth `H(x + 1) + H(n - x) - 2`… -/theorem random_bst_depth (n x : Nat) (hx : x < n) :    Treap.Random.average (fun _ => 1) (Finset.range n) (fun xs => ((insertKeys xs).erase.depth x : ℝ)) =      ((harmonic (x + 1) : ℚ) : ℝ) + ((harmonic (n - x) : ℚ) : ℝ) - 2 :=  Random.random_bst_depth n x hx
theoremClassical.Random.Results.random_bst_depth_lepropext · Classical.choice · Quot.soundClassical/Random/Abstract.lean:44
/-- …at most `2 ln n`. -/theorem random_bst_depth_le (n x : Nat) (hx : x < n) :    Treap.Random.average (fun _ => 1) (Finset.range n) (fun xs => ((insertKeys xs).erase.depth x : ℝ)) ≤      2 * Real.log n :=  Random.random_bst_depth_le n x hx

Summing over the searches, a random BST serves mm searches at expected cost at most m(1+2ln⁡n)≈m(1+1.39log⁡2n)m(1 + 2\ln n) \approx m(1 + 1.39 \log_2 n); the library states the bound per key, not this sum. The Isabelle formalization of Eberl et al. (2020) covers similar ground.

22.2 Treaps

Treaps (Seidel and Aragon 1996) keep the distribution under updates. Each key draws a random priority when it is inserted. An insertion adds the key as a leaf, then rotates it up while its priority is smaller than its parent’s. A deletion rotates the key down until it is a leaf, then removes it. The trees are the Cartesian trees of Vuillemin (1980), maintained dynamically.

Because the treap for given keys and priorities is unique, the shape after any sequence of updates depends only on the current keys and their priorities, not on the order of the updates. With random priorities it is always a random BST.

Not yet formalized
  • Treap insertion and deletion produce the treap of the new key set.
  • An insertion or a deletion makes fewer than 2 rotations in expectation.

Roadmap entry 9.

22.3 Other ways to sample

Randomized BSTs (Martínez and Roura 1998) replace stored priorities by subtree sizes and fresh random choices at each insertion. A new key becomes the root of a subtree of size ss with probability 1/(s+1)1/(s + 1). The tree is again a random BST after every operation. Zip trees (Tarjan et al. 2021) store small random ranks, drawn from a geometric distribution, and break ties by key. Their insertions and deletions unzip and zip a search path instead of rotating. Their shape is a treap for these ranks, with expected depths that are also logarithmic. They belong in this chapter as further samplers of a treap. Each needs one theorem relating it to the treap, not a separate analysis.

Not yet formalized

Randomized BSTs produce the random BST after every operation. Zip trees produce the treap of their ranks.

Roadmap entry 9.

22.4 Height

The expected depth of a single key is about 2ln⁡n2 \ln n. The height of a random BST, the largest depth, is larger: about 4.311ln⁡n4.311 \ln n in expectation (Devroye 1986), and concentrated around that value (Reed 2003; Drmota 2003). This is a hard proof. It is a stretch goal in the roadmap (S2).