Chapter 19Static search trees
A static tree never changes. It is built once, and then serves every request by an ordinary search from the root. Serving key costs one unit plus the depth of : this is StaticTree.cost, and Chapter 14 shows that it is exactly the cost of a pointer-machine execution that never rotates.
A static tree can know two things in advance: the number of keys, or how often each key will be requested. The first gives the balanced tree, which has the best possible worst-case guarantee. The second gives entropy trees and optimal trees, which are the benchmark behind static optimality. The two headline results are the worst-case baseline and the optimal tree:
The balanced tree on keys serves every sequence of searches at cost at most , counting one unit per search plus the depth of the requested key. Conversely, every tree on keys has a key such that searching times costs at least .
In Lean, the balanced tree is Tree.balanced and the cost is StaticTree.cost. The repeated sequence is List.replicate m x.
The Lean statements
/-- Searching the balanced tree costs at most `1 + ⌊log₂ n⌋` per request. -/theorem balanced_cost (n : Nat) (xs : List Nat) (valid : ∀ x ∈ xs, x < n) : StaticTree.cost (balanced n) xs ≤ xs.length * (Nat.log2 n + 1) := … Static.balanced_cost n xs validModels.Rotation, Models.Online, Bounds.StaticTree.Definitions, Bounds.Logarithmic/-- No static tree does better in the worst case: repeating a deepest key `m`times costs at least `m(1 + ⌊log₂ n⌋)`. -/theorem exists_expensive (t : Tree) (h : 0 < t.size) (m : Nat) : ∃ x < t.size, m * (Nat.log2 t.size + 1) ≤ StaticTree.cost t (List.replicate m x) := … Static.exists_expensive t h mModels.Rotation, Models.Online, Bounds.StaticTree.Definitions, Bounds.LogarithmicFor every sequence of requests to keys, the dynamic program builds a tree on the keys whose search cost for is at most that of every other tree on the same keys. Knuth’s algorithm computes this optimal cost while examining at most candidate roots; the library proves that it returns the cost, not that a tree built from its root table is optimal.
In Lean, the weights are the request counts Static.counts, the optimal tree and cost are Static.optTree and Static.optCost, and Knuth’s algorithm is Optimal.knuth, which returns the cost and the number of roots it examined.
The Lean statements
theorem optTree_static (n : Nat) (xs : List Nat) (valid : ∀ x ∈ xs, x < n) : (optTree (counts n xs)).size = n ∧ StaticTree.cost (optTree (counts n xs)) xs = optCost (counts n xs) := … ⟨Static.optTree_counts_size n xs, Static.optTree_static n xs valid⟩theorem optCost_le_static (n : Nat) (xs : List Nat) (t : Tree) (ht : t.size = n) (valid : ∀ x ∈ xs, x < n) : optCost (counts n xs) ≤ StaticTree.cost t xs := … Static.optCost_le_static n xs t ht validtheorem knuth_optCost (w : List Nat) : (knuth (rangeWeight w) w.length).1 = optCost w := … Static.knuth_optCost wtheorem knuth_steps_le (w : List Nat) : (knuth (rangeWeight w) w.length).2 ≤ 2 * w.length ^ 2 := … Static.knuth_steps_le w19.1 Balanced trees
The library builds one balanced tree for every number of keys. The root takes the middle rank, and the larger half goes to the left:
/-- The balanced tree on `n` keys. The root takes the middle rank; the leftsubtree gets `⌈(n-1)/2⌉` keys and the right subtree `⌊(n-1)/2⌋`, so the twosizes differ by at most one. -/def Tree.balanced : Nat → Tree | 0 => .nil | n + 1 => .node (balanced ((n + 1) / 2)) (balanced (n / 2))termination_by n => ntermination_by n => n tells Lean that the recursion terminates because both halves, (n + 1) / 2 and n / 2, are smaller than n + 1. The two subtree sizes differ by at most one. When the balanced tree is the perfect tree Tango.perfect with levels, as one can check by unfolding the definitions (no theorem states it); Tango uses both as reference trees (Section 26.1).
Theorem (balanced trees). The balanced tree on keys has keys, and every key lies at depth at most . For its height, in nodes, is exactly .
/-- The balanced tree has `n` keys (`Tree.balanced_size`). -/theorem balanced_size (n : Nat) : (balanced n).size = n := Tree.balanced_size nModels.Rotation, Models.Online, Bounds.StaticTree.Definitions, Bounds.Logarithmic/-- Every key of the balanced tree lies at depth at most `⌊log₂ n⌋`. -/theorem balanced_depth (n x : Nat) (hx : x < n) : (balanced n).depth x ≤ Nat.log2 n := Static.balanced_depth n x hxModels.Rotation, Models.Online, Bounds.StaticTree.Definitions, Bounds.Logarithmic/-- The balanced tree has height `⌊log₂ n⌋ + 1`… -/theorem balanced_height_eq (n : Nat) (h : 0 < n) : height (balanced n) = Nat.log2 n + 1 := Static.balanced_height_eq n hModels.Rotation, Models.Online, Bounds.StaticTree.Definitions, Bounds.LogarithmicNo tree does better. A tree whose height is nodes holds at most keys, so:
Theorem (minimum height). Every tree on keys has height at least , and a key at depth at least .
/-- …the minimum: every nonempty tree has height at least `⌊log₂ n⌋ + 1`. -/theorem log2_add_one_le_height (t : Tree) (h : 0 < t.size) : Nat.log2 t.size + 1 ≤ height t := Static.log2_add_one_le_height t hModels.Rotation, Models.Online, Bounds.StaticTree.Definitions, Bounds.Logarithmic/-- Conversely, every nonempty tree has a key at depth at least `⌊log₂ n⌋`. -/theorem exists_deep (t : Tree) (h : 0 < t.size) : ∃ x < t.size, Nat.log2 t.size ≤ t.depth x := Static.exists_deep t hModels.Rotation, Models.Online, Bounds.StaticTree.Definitions, Bounds.LogarithmicSearching costs one plus the depth, which gives the two halves of the headline result, and the comparison with the logarithmic baseline Bounds.logCost of Chapter 14:
Theorem (the baseline). Searching the balanced tree costs at most , hence at most . Every nonempty tree has a key whose -fold repetition costs at least .
/-- Searching the balanced tree costs at most `1 + ⌊log₂ n⌋` per request. -/theorem balanced_cost (n : Nat) (xs : List Nat) (valid : ∀ x ∈ xs, x < n) : StaticTree.cost (balanced n) xs ≤ xs.length * (Nat.log2 n + 1) := Static.balanced_cost n xs validModels.Rotation, Models.Online, Bounds.StaticTree.Definitions, Bounds.Logarithmic/-- The same bound against the real-valued baseline. -/theorem balanced_cost_le_logCost (n : Nat) (xs : List Nat) (valid : ∀ x ∈ xs, x < n) : (StaticTree.cost (balanced n) xs : ℝ) ≤ Bounds.logCost n xs := Static.balanced_cost_le_logCost n xs validModels.Rotation, Models.Online, Bounds.StaticTree.Definitions, Bounds.Logarithmic/-- No static tree does better in the worst case: repeating a deepest key `m`times costs at least `m(1 + ⌊log₂ n⌋)`. -/theorem exists_expensive (t : Tree) (h : 0 < t.size) (m : Nat) : ∃ x < t.size, m * (Nat.log2 t.size + 1) ≤ StaticTree.cost t (List.replicate m x) := Static.exists_expensive t h mModels.Rotation, Models.Online, Bounds.StaticTree.Definitions, Bounds.Logarithmic19.2 Entropy trees
Suppose that key is requested times among requests. A tree in which has depth about serves the requests at cost about the entropy bound Bounds.staticCost. Both directions are formalized (Chapter 14):
- Lower bound. Every static tree costs at least a third of the entropy bound (
Results.entropy_lower_bound). - Upper bound. Some static tree costs at most the entropy bound (
Results.entropy_upper_bound).
The tree of the upper bound is built by a rule close to that of Mehlhorn (1975): put the weighted median at the root and recurse on both sides. This is the weighted search tree of Chapter 34, where every key of weight lands at depth at most . With weights on the keys only, the library’s bound is already the entropy plus one unit per request, with no constant factor. Mehlhorn’s analyses (Mehlhorn 1975; Mehlhorn 1977) also allow weights on the gaps between keys, for unsuccessful searches; they are not formalized.
19.3 Optimal static trees
The entropy tree is within a constant factor of the best static tree. The best static tree itself can be computed exactly, by dynamic programming over intervals of keys. The library writes intervals half-open: holds the keys . Let be the weight of the interval. A tree on puts some key at its root, and every search in the interval passes through the root. So the cheapest tree uses the cheapest trees on both sides:
Computed directly this takes time; Gilbert and Moore (1959) used the same recurrence when only the gaps carry weight. Knuth (1971) observed that the optimal roots are monotone: some optimal root of lies between optimal roots of and of . Restricting the minimum to that window makes the total work . Yao (1980) explained why: whenever the weight satisfies the quadrangle inequality and is monotone on nested intervals, the cost satisfies the quadrangle inequality too, and that makes the optimal roots monotone.
The library follows Yao. Everything is stated for an abstract interval weight W, and key weights are one instance. Weights on the gaps between keys, for unsuccessful searches, would be another additive instance; it is not stated separately, because in the models of this book every request is a key.
19.3.1 The recurrence
/-- The cubic recurrence `C(i, j) = W(i, j) + min_{i ≤ r < j} (C(i, r) + C(r + 1, j))`,with `C(i, j) = 0` for an empty interval. -/def cost (W : Nat → Nat → Nat) (i j : Nat) : Nat := if i < j then W i j + ((List.finRange (j - i)).map fun r : Fin (j - i) => cost W i (i + r) + cost W (i + r + 1) j).foldr min (cost W i i + cost W (i + 1) j) else 0termination_by j - idecreasing_by all_goals omega/-- The cost of the interval `[i, j)` with root `r`. -/def candidate (W : Nat → Nat → Nat) (i j r : Nat) : Nat := W i j + cost W i r + cost W (r + 1) j/-- The largest optimal root of `[i, j)` (Knuth's `R(i, j)`); `i` when theinterval is empty. -/def root (W : Nat → Nat → Nat) (i j : Nat) : Nat := i + Nat.findGreatest (fun d => candidate W i j (i + d) = cost W i j) (j - i - 1)/-- The tree built from the largest optimal roots. -/def tree (W : Nat → Nat → Nat) (i j : Nat) : Tree := if i < j then .node (tree W i (root W i j)) (tree W (root W i j + 1) j) else .niltermination_by j - idecreasing_by all_goals have := Nat.findGreatest_le (P := fun d => candidate W i j (i + d) = cost W i j) (j - i - 1) simp only [root] omegacost W i j is the recurrence, with the minimum written as a fold over the roots i + r for r < j - i. root W i j is Knuth’s , the largest optimal root, found by Nat.findGreatest; any consistent choice would do, and the largest one makes the monotonicity statements below hold as written. tree W i j builds the tree from these roots.
The cost of an arbitrary tree is the weight of the interval of every subtree, summed over all subtrees. This is LazyFinger.intervalCost of Chapter 15, the same sum that the optimal lazy-finger tree uses. With key weights it is the weighted depth , as shown below.
Theorem (the recurrence is optimal). tree W i j has the keys of the interval, its cost is cost W i j, and no tree on those keys costs less.
/-- The recurrence builds a tree on the keys of `[i, j)`… -/theorem tree_size (W : Nat → Nat → Nat) (i j : Nat) : (tree W i j).size = j - i := Optimal.tree_size W i j/-- …whose cost is the value of the recurrence… -/theorem tree_cost (W : Nat → Nat → Nat) (i j : Nat) : LazyFinger.intervalCost W (tree W i j) i = cost W i j := Optimal.tree_cost W i j/-- …and no tree on those keys costs less. -/theorem cost_le_intervalCost (W : Nat → Nat → Nat) (t : Tree) (i j : Nat) (h : t.size = j - i) : cost W i j ≤ LazyFinger.intervalCost W t i := Optimal.cost_le_intervalCost W t i j h19.3.2 Yao’s quadrangle inequality
/-- The quadrangle inequality `W(i, j) + W(i', j') ≤ W(i', j) + W(i, j')` for`i ≤ i' ≤ j ≤ j'`. -/def Quadrangle (W : Nat → Nat → Nat) : Prop := ∀ i i' j j', i ≤ i' → i' ≤ j → j ≤ j' → W i j + W i' j' ≤ W i' j + W i j'/-- Monotonicity under inclusion: `W(i', j) ≤ W(i, j')` when `[i', j) ⊆ [i, j')`. -/def InclusionMonotone (W : Nat → Nat → Nat) : Prop := ∀ i i' j j', i ≤ i' → i' ≤ j → j ≤ j' → W i' j ≤ W i j'Theorem (Yao; Knuth’s inequalities). If the weight satisfies the quadrangle inequality and is monotone under inclusion, then the optimal cost satisfies the quadrangle inequality too, and the largest optimal roots are monotone: and .
/-- **Yao.** The optimal cost inherits the quadrangle inequality from amonotone interval weight. -/theorem cost_quadrangle (W : Nat → Nat → Nat) (hQ : Quadrangle W) (hM : InclusionMonotone W) : Quadrangle (cost W) := Optimal.cost_quadrangle hQ hM/-- **Knuth's inequalities**, first half: `R(i, j) ≤ R(i, j + 1)`. -/theorem root_le_root_right (W : Nat → Nat → Nat) (hQ : Quadrangle W) (hM : InclusionMonotone W) {i j : Nat} (h : i < j) : root W i j ≤ root W i (j + 1) := Optimal.root_le_root_right hQ hM h/-- **Knuth's inequalities**, second half: `R(i, j) ≤ R(i + 1, j)`. -/theorem root_le_root_left (W : Nat → Nat → Nat) (hQ : Quadrangle W) (hM : InclusionMonotone W) {i j : Nat} (h : i + 1 < j) : root W i j ≤ root W (i + 1) j := Optimal.root_le_root_left hQ hM h19.3.3 Knuth’s algorithm
Knuth’s algorithm fills the table of costs and roots by increasing interval length. For an interval of length at least two it examines only the roots between and . Along each diagonal of the table these windows overlap only at their ends, so a whole diagonal examines roots, and the whole table .
/-- Among the roots `lo ≤ r ≤ hi`, the least candidate cost and the largestroot attaining it. Each root examined is one step. -/def scan (W : Nat → Nat → Nat) (C : Nat → Nat → Nat) (i j lo hi : Nat) : Nat × Nat := (List.range' (lo + 1) (hi - lo)).foldl (fun best r => if W i j + C i r + C (r + 1) j ≤ best.1 then (W i j + C i r + C (r + 1) j, r) else best) (W i j + C i lo + C (lo + 1) j, lo)/-- One table entry of Knuth's algorithm, from tables `C`, `K` filled for allshorter intervals: (cost, root, steps). A single key is its own root; a longerinterval searches only between the roots of its two maximal subintervals. -/def knuthEntry (W : Nat → Nat → Nat) (C K : Nat → Nat → Nat) (i j : Nat) : Nat × Nat × Nat := if j = i + 1 then (W i j, i, 1) else let lo := K i (j - 1) let hi := K (i + 1) j let best := scan W C i j lo hi (best.1, best.2, hi + 1 - lo)/-- Knuth's tables for all intervals of `[0, n)` of length at most `len`, byincreasing length, with the total number of steps. -/def knuthTables (W : Nat → Nat → Nat) (n : Nat) : Nat → (Nat → Nat → Nat) × (Nat → Nat → Nat) × Nat | 0 => (fun _ _ => 0, fun i _ => i, 0) | len + 1 => let prev := knuthTables W n len let entry := fun i => knuthEntry W prev.1 prev.2.1 i (i + len + 1) (fun i j => if j = i + len + 1 then (entry i).1 else prev.1 i j, fun i j => if j = i + len + 1 then (entry i).2.1 else prev.2.1 i j, prev.2.2 + ((List.range (n - len)).map fun i => (entry i).2.2).sum)/-- Knuth's `O(n²)` algorithm on `[0, n)`: (optimal cost, steps). -/def knuth (W : Nat → Nat → Nat) (n : Nat) : Nat × Nat := let t := knuthTables W n n (t.1 0 n, t.2.2)Theorem (Knuth). Under the same two hypotheses, Knuth’s algorithm returns the optimal cost of and examines at most candidate roots.
/-- Knuth's algorithm computes the recurrence… -/theorem knuth_cost (W : Nat → Nat → Nat) (hQ : Quadrangle W) (hM : InclusionMonotone W) (n : Nat) : (knuth W n).1 = cost W 0 n := Optimal.knuth_cost hQ hM n/-- …examining at most `2n²` candidate roots. -/theorem knuth_steps (W : Nat → Nat → Nat) (hQ : Quadrangle W) (hM : InclusionMonotone W) (n : Nat) : (knuth W n).2 ≤ 2 * n ^ 2 := Optimal.knuth_steps hQ hM nknuth returns a count of the candidate roots it examines, not a running time in a machine model. Each examination is a constant number of table lookups and additions, so the count is the usual measure of the algorithm’s work. The tables are functions in Lean, not arrays, so the Lean evaluation itself is not quadratic.
19.3.4 Key weights and request sequences
For key weights , the interval weight is the sum of the weights in the interval:
/-- The weighted search cost of a tree: `∑ₓ w[x] · (depth x + 1)`. -/def weightedCost (w : List Nat) (t : Tree) : Nat := ∑ x ∈ Finset.range t.size, w.getD x 0 * (t.depth x + 1)/-- The total key weight of the interval `[i, j)`. -/def rangeWeight (w : List Nat) (i j : Nat) : Nat := ∑ x ∈ Finset.Ico i j, w.getD x 0/-- The optimal weighted cost over trees on the `w.length` keys, by the recurrence. -/def optCost (w : List Nat) : Nat := Optimal.cost (rangeWeight w) 0 w.length/-- An optimal tree, built from the largest optimal roots. -/def optTree (w : List Nat) : Tree := Optimal.tree (rangeWeight w) 0 w.length/-- Request counts of the keys `0, …, n - 1`. -/def counts (n : Nat) (xs : List Nat) : List Nat := (List.range n).map xs.countTheorem (key weights). Interval sums satisfy the quadrangle inequality (in fact with equality) and are monotone under inclusion. The interval cost of a tree is its weighted depth. The optimal tree has keys and costs optCost w, no tree costs less, and Knuth’s algorithm computes this cost with at most steps.
theorem rangeWeight_quadrangle (w : List Nat) : Quadrangle (rangeWeight w) := Static.rangeWeight_quadrangle wtheorem rangeWeight_monotone (w : List Nat) : InclusionMonotone (rangeWeight w) := Static.rangeWeight_monotone w/-- The subtree-weight cost is the weighted depth cost. -/theorem weightedCost_eq_intervalCost (w : List Nat) (t : Tree) : weightedCost w t = LazyFinger.intervalCost (rangeWeight w) t 0 := Static.weightedCost_eq_intervalCost w ttheorem optTree_size (w : List Nat) : (optTree w).size = w.length := Static.optTree_size wtheorem optTree_cost (w : List Nat) : weightedCost w (optTree w) = optCost w := Static.optTree_cost wtheorem optCost_le (w : List Nat) (t : Tree) (h : t.size = w.length) : optCost w ≤ weightedCost w t := Static.optCost_le w t htheorem knuth_optCost (w : List Nat) : (knuth (rangeWeight w) w.length).1 = optCost w := Static.knuth_optCost wtheorem knuth_steps_le (w : List Nat) : (knuth (rangeWeight w) w.length).2 ≤ 2 * w.length ^ 2 := Static.knuth_steps_le wWith the request counts of a sequence as weights, the weighted cost is the static search cost. So optCost (counts n xs) is , the cost of the best static tree in the map of the bounds, and it lies between a third of the entropy bound and the entropy bound:
Theorem (the best static tree for a sequence). Searching a tree costs its weighted cost under the request counts. The optimal tree for the counts serves the sequence at cost optCost, and every tree on the same keys costs at least that much. This optimum is between a third of the entropy bound and the entropy bound, and at most .
/-- Searching a fixed tree from the root costs its weighted cost under therequest counts. -/theorem staticCost_eq_weightedCost (t : Tree) (xs : List Nat) (valid : ∀ x ∈ xs, x < t.size) : StaticTree.cost t xs = weightedCost (counts t.size xs) t := Static.staticCost_eq_weightedCost t xs validtheorem optTree_static (n : Nat) (xs : List Nat) (valid : ∀ x ∈ xs, x < n) : (optTree (counts n xs)).size = n ∧ StaticTree.cost (optTree (counts n xs)) xs = optCost (counts n xs) := ⟨Static.optTree_counts_size n xs, Static.optTree_static n xs valid⟩theorem optCost_le_static (n : Nat) (xs : List Nat) (t : Tree) (ht : t.size = n) (valid : ∀ x ∈ xs, x < n) : optCost (counts n xs) ≤ StaticTree.cost t xs := Static.optCost_le_static n xs t ht valid/-- The best static tree lies between a third of the entropy bound and theentropy bound itself. -/theorem optCost_entropy (n : Nat) (xs : List Nat) (valid : ∀ x ∈ xs, x < n) : Bounds.staticCost n xs ≤ 3 * (optCost (counts n xs) : ℝ) ∧ (optCost (counts n xs) : ℝ) ≤ Bounds.staticCost n xs := ⟨Static.entropy_le_optCost n xs valid, Static.optCost_le_entropy n xs valid⟩theorem optCost_le_balanced (n : Nat) (xs : List Nat) (valid : ∀ x ∈ xs, x < n) : optCost (counts n xs) ≤ xs.length * (Nat.log2 n + 1) := Static.optCost_le_balanced n xs validThe Isabelle Archive of Formal Proofs has a formalization of the same three steps, the recurrence, Yao’s inequality and Knuth’s algorithm (Nipkow and Somogyi 2018).
19.4 Further results
When only the gaps carry weight, the searches all end at leaves, and the problem becomes that of optimal alphabetic codes. The algorithms of Hu and Tucker (1971) and Garsia and Wachs (1977) solve it in time. They are listed as a stretch goal in the roadmap (S3).