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

Chapter 21Weight-balanced trees

Rank-balanced trees balance heights. Weight-balanced trees balance sizes. Let the weight of a subtree be its number of keys plus one, its number of empty leaves. A tree is β\beta-balanced, for a constant β<1\beta < 1, when every child’s weight is at most β\beta times its parent’s. Along any root-to-leaf path the weight then shrinks by a factor β\beta at each step, so the height is at most log⁡1/β(n+1)\log_{1/\beta}(n + 1).

There are two ways to restore the invariant after an update. BB[α] trees use rotations at the unbalanced node. Scapegoat trees rebuild a whole subtree into a balanced one. The library formalizes the invariant, rebuilding, and scapegoat trees; BB[α] rebalancing is not formalized yet.

Weight-balanced trees have logarithmic height, and a subtree can be rebuilt with two rotations per key

If every child’s weight is at most β\beta times its parent’s, for some 0<β<10 < \beta < 1, then the height, in nodes, is at most log⁡1/β(n+1)\log_{1/\beta}(n + 1). Every tree on nn keys can be turned into the balanced tree on the same keys by at most 2n2n rotations.

In Lean, the invariant is WeightBalanced.Balanced and rebuilding is WeightBalanced.rebuild, which returns the balanced tree Tree.balanced with a number of rotations; rebuild_rotations proves that this many rotations reach it.

The Lean statements
theoremClassical.WeightBalanced.Results.height_lepropext · Classical.choice · Quot.soundClassical/WeightBalanced/Abstract.lean:16
/-- **Height of trees of bounded balance.** If every child's weight is at most`β` times its parent's, the height is at most `log_{1/β}(n + 1)`. -/theorem height_le (β : ℝ) (hβ : 0 < β ∧ β < 1) (t : Tree) (h : Balanced β t) :    (height t : ℝ) ≤ Real.logb (1 / β) (t.size + 1) := …  WeightBalanced.height_le β hβ t h
theoremClassical.WeightBalanced.Results.rebuild_rotationspropext · Quot.soundClassical/WeightBalanced/Abstract.lean:33
/-- …by exactly the reported number of rotations… -/theorem rebuild_rotations (t : Tree) : Rotations t (rebuild t).1 (rebuild t).2 := …  WeightBalanced.rebuild_rotations t
theoremClassical.WeightBalanced.Results.rebuild_costpropext · Quot.soundClassical/WeightBalanced/Abstract.lean:37
/-- …at most two per key. -/theorem rebuild_cost (t : Tree) : (rebuild t).2 ≤ 2 * t.size := …  WeightBalanced.rebuild_cost t
10 definitions in 4 chapters · reading list
Scapegoat trees keep logarithmic depth with O(log⁡n)O(\log n) amortized cost per update

Fix a rational 12<α<1\frac12 < \alpha < 1. Start from the empty tree, and run any valid sequence of accesses, insertions and deletions with the scapegoat algorithm. The run is an execution of the dictionary model. At every point, every key lies at depth at most log⁡1/αn+1\log_{1/\alpha} n + 1. The total cost, rebuilding included, is at most ∑ib(ni)\sum_i b(n_i), where nin_i is the number of keys before the ii-th operation and b(n)=O(log⁡n)b(n) = O(\log n) is an explicit bound.

In Lean, the algorithm is Scapegoat.run, the dictionary execution is Dictionary.Execution of Chapter 6, and the bound is Scapegoat.bound.

The Lean statements
theoremClassical.Scapegoat.Results.run_executionpropext · Classical.choice · Quot.soundClassical/Scapegoat/Abstract.lean:21
/-- A run is a dictionary execution with the reported cost. -/theorem run_execution (α : ℚ) (s : State) (ops : List Op) (valid : Op.ValidSeq s.1.size ops) :    Dictionary.Execution s.1.unit ops (run α s ops).1.1.unit (run α s ops).2 0 := …  Scapegoat.run_execution s ops valid
theoremClassical.Scapegoat.Results.reachable_depthpropext · Classical.choice · Quot.soundClassical/Scapegoat/Abstract.lean:26
/-- **Height.** From the empty tree, every key always lies at depth at most`log_{1/α} n + 1`. -/theorem reachable_depth (α : ℚ) (hα : 1 / 2 < α ∧ α < 1) (ops : List Op)    (valid : Op.ValidSeq 0 ops) (z : Nat) (hz : z < (run α (.nil, 0) ops).1.1.size) :    ((run α (.nil, 0) ops).1.1.depth z : ℝ) ≤ Real.logb (1 / α) (run α (.nil, 0) ops).1.1.size + 1 := …  Scapegoat.reachable_depth hα ops valid z hz
theoremClassical.Scapegoat.Results.total_costpropext · Classical.choice · Quot.soundClassical/Scapegoat/Abstract.lean:33
/-- **Amortized cost.** From the empty tree, the total cost, rebuildingincluded, is at most `∑ bound α nᵢ` over the key counts `nᵢ` met by theoperations: `O(log n)` per operation. -/theorem total_cost (α : ℚ) (hα : 1 / 2 < α ∧ α < 1) (ops : List Op) (valid : Op.ValidSeq 0 ops) :    ((run α (.nil, 0) ops).2 : ℝ) ≤ ((sizesFrom 0 ops).map (bound α)).sum := …  Scapegoat.total_cost hα ops valid
31 definitions in 5 chapters · reading list

21.1 The invariant

defClassical.WeightBalanced.weightno axiomsClassical/WeightBalanced/Definitions/Abstract.lean:13
/-- The number of empty leaves: size plus one. -/def weight (t : Tree) : Nat := t.size + 1
defClassical.WeightBalanced.Balancedpropext · Classical.choice · Quot.soundClassical/WeightBalanced/Definitions/Abstract.lean:16
/-- Every child's weight is at most `β` times its parent's. -/def Balanced (β : ℝ) : Tree → Prop  | .nil => True  | .node l r =>      (weight l : ℝ) ≤ β * weight (.node l r) ∧ (weight r : ℝ) ≤ β * weight (.node l r) ∧        Balanced β l ∧ Balanced β r

Theorem (height). If a tree is β\beta-balanced, for 0<β<10 < \beta < 1, then its height, in nodes, is at most log⁡1/β(n+1)\log_{1/\beta}(n + 1). The balanced tree on nn keys is β\beta-balanced for every β≥23\beta \ge \frac23.

theoremClassical.WeightBalanced.Results.height_lepropext · Classical.choice · Quot.soundClassical/WeightBalanced/Abstract.lean:16
/-- **Height of trees of bounded balance.** If every child's weight is at most`β` times its parent's, the height is at most `log_{1/β}(n + 1)`. -/theorem height_le (β : ℝ) (hβ : 0 < β ∧ β < 1) (t : Tree) (h : Balanced β t) :    (height t : ℝ) ≤ Real.logb (1 / β) (t.size + 1) :=  WeightBalanced.height_le β hβ t h
theoremClassical.WeightBalanced.Results.balanced_balancedpropext · Classical.choice · Quot.soundClassical/WeightBalanced/Abstract.lean:22
/-- The balanced tree is `β`-balanced for every `β ≥ 2/3`. -/theorem balanced_balanced (β : ℝ) (hβ : 2 / 3 ≤ β) (n : Nat) : Balanced β (balanced n) :=  WeightBalanced.balanced_balanced β hβ n

The constant 23\frac23 comes from the smallest trees: a root with one child has weights 22 and 33.

The invariant has one property that a height condition lacks. Suppose a subtree of weight ss has just been balanced. Then Ω((β−12) s)\Omega((\beta - \frac12)\, s) insertions and deletions must happen inside it before it can violate the invariant again. So work proportional to ss, spent to restore the balance at that node, can be charged to the updates that broke it. Each update lies below O(log⁡n)O(\log n) nodes, so it is charged O(log⁡n)O(\log n) times in total. The scapegoat analysis below makes this argument precise, with a potential.

21.2 Rebuilding

In the rotation model, rebuilding needs no new tool. The reset theorem of Chapter 3 turns any tree into any other of the same size with at most 2n2n rotations, by rotating both into the right spine. Rebuilding applies the same idea with the balanced tree as the target, and counts the rotations exactly:

defClassical.WeightBalanced.vineCostno axiomsClassical/WeightBalanced/Definitions/Abstract.lean:23
/-- Rotations used to turn a tree into its right spine: the root's leftsubtree is emptied one right rotation per node, then the rest of the spine. -/def vineCost : Tree → Nat  | .nil => 0  | .node l r => l.size + vineCost r
defClassical.WeightBalanced.rebuildpropext · Quot.soundClassical/WeightBalanced/Definitions/Abstract.lean:29
/-- Rebuild a tree into the balanced tree on its keys: rotate to the rightspine, then run the same procedure for the balanced tree backwards. Returnsthe new tree and the number of rotations. -/def rebuild (t : Tree) : Tree × Nat :=  (Tree.balanced t.size, vineCost t + vineCost (Tree.balanced t.size))

vineCost t is the number of right rotations that turn t into its right spine: each node of the root’s left subtree is rotated over the root once, and then the rest of the spine is done the same way. rebuild t returns the balanced tree on t.size keys, and the number of rotations of two phases: from t to the spine, and from the spine to the balanced tree, which is the first phase for the balanced tree, run backwards.

Theorem (rebuilding). rebuild t is the balanced tree on the keys of t, of minimum height ⌊log⁡2n⌋+1\lfloor\log_2 n\rfloor + 1. It is reached from t by exactly the reported number of rotations, which is at most 2n2n.

theoremClassical.WeightBalanced.Results.rebuild_treepropext · Quot.soundClassical/WeightBalanced/Abstract.lean:26
/-- Rebuilding produces the balanced tree on the same keys… -/theorem rebuild_tree (t : Tree) : (rebuild t).1 = balanced t.size := rfl
theoremClassical.WeightBalanced.Results.rebuild_heightpropext · Classical.choice · Quot.soundClassical/WeightBalanced/Abstract.lean:29
/-- …of minimum height… -/theorem rebuild_height (t : Tree) (h : 0 < t.size) : height (rebuild t).1 = Nat.log2 t.size + 1 :=  Static.balanced_height_eq t.size h
theoremClassical.WeightBalanced.Results.rebuild_rotationspropext · Quot.soundClassical/WeightBalanced/Abstract.lean:33
/-- …by exactly the reported number of rotations… -/theorem rebuild_rotations (t : Tree) : Rotations t (rebuild t).1 (rebuild t).2 :=  WeightBalanced.rebuild_rotations t
theoremClassical.WeightBalanced.Results.rebuild_costpropext · Quot.soundClassical/WeightBalanced/Abstract.lean:37
/-- …at most two per key. -/theorem rebuild_cost (t : Tree) : (rebuild t).2 ≤ 2 * t.size :=  WeightBalanced.rebuild_cost t

The Day–Stout–Warren algorithm (Day 1976; Stout and Warren 1986) follows the same plan, a vine and back, in linear time and constant extra space. Its second phase compresses the vine into a tree of minimum height that is not exactly Tree.balanced, so the library uses its own second phase. The library specifies rebuilding by its result and its count, and proves that a sequence of that many rotations exists; it does not execute the rotations one by one, and does not model the running time of a rebuilding procedure.

21.3 Restoring by rebuilding: scapegoat trees

Scapegoat trees (Andersson 1989; Galperin and Rivest 1993) store no balance information at all. Insertions and deletions are the plain ones, without rebalancing. Balance is restored only occasionally, by rebuilding a subtree.

defClassical.Scapegoat.bstDeletepropextClassical/Scapegoat/Definitions/Abstract.lean:17
/-- Delete rank `x` without rebalancing: a node with at most one child isspliced out; a node with two children loses its successor instead. -/def bstDelete : Tree → Nat → Tree  | .nil, _ => .nil  | .node l r, x =>      if x < l.size then .node (bstDelete l x) r      else if x = l.size then        match l, r with        | .nil, _ => r        | _, .nil => l        | _, _ => .node l (bstDelete r 0)      else .node l (bstDelete r (x - l.size - 1))
defClassical.Scapegoat.deleteTargetpropextClassical/Scapegoat/Definitions/Abstract.lean:30
/-- The rank of the node that `bstDelete` removes: `x`, or its successor `x + 1`when the node of rank `x` has two children. -/def deleteTarget : Tree → Nat → Nat  | .nil, x => x  | .node l r, x =>      if x < l.size then deleteTarget l x      else if x = l.size then        match l, r with        | .nil, _ => x        | _, .nil => x        | _, _ => x + 1      else l.size + 1 + deleteTarget r (x - l.size - 1)

A deletion splices out the node, or its successor when the node has two children (Chapter 6). Insertion is Tree.insertAt, which adds a leaf at the gap.

The algorithm keeps one number besides the tree: NN, the largest number of keys since the last rebuild triggered by a deletion.

  • Insertion. If the new leaf lands at depth dd with αdN<1\alpha^d N < 1, that is d>log⁡1/αNd > \log_{1/\alpha} N, find the deepest subtree on its search path that is too tall for its size, the scapegoat, and rebuild it.
  • Deletion. If fewer than αN\alpha N keys remain, rebuild the whole tree, and set NN to the number of keys.
  • Access. Search, and change nothing.
defClassical.Scapegoat.Violatespropext · Classical.choice · Quot.soundClassical/Scapegoat/Definitions/Abstract.lean:43
/-- The subtree is too tall for its size: the node of rank `k` lies at depth`d` with `α^d · size < 1`, that is `d > log_{1/α} size`. -/def Violates (α : ℚ) (t : Tree) (k : Nat) : Prop := α ^ t.depth k * t.size < 1
instanceClassical.Scapegoat.instDecidableViolatespropext · Classical.choice · Quot.soundClassical/Scapegoat/Definitions/Abstract.lean:47
instance (α : ℚ) (t : Tree) (k : Nat) : Decidable (Violates α t k) := by  unfold Violates; infer_instance
defClassical.Scapegoat.fixpropext · Classical.choice · Quot.soundClassical/Scapegoat/Definitions/Abstract.lean:50
/-- Rebuild the deepest subtree on the search path to `k` that violates theheight condition, if any; return the new tree and the rotations used. -/def fix (α : ℚ) : Tree → Nat → Option (Tree × Nat)  | .nil, _ => none  | .node l r, k =>      let below : Option (Tree × Nat) :=        if k < l.size then (fix α l k).map fun p => (.node p.1 r, p.2)        else if k = l.size then none        else (fix α r (k - l.size - 1)).map fun p => (.node l p.1, p.2)      match below with      | some p => some p      | none => if Violates α (.node l r) k then some (rebuild (.node l r)) else none
defClassical.Scapegoat.Stateno axiomsClassical/Scapegoat/Definitions/Abstract.lean:63
/-- A scapegoat tree: the shape and the count `N`. -/abbrev State := Tree × Nat
defClassical.Scapegoat.steppropext · Classical.choice · Quot.soundClassical/Scapegoat/Definitions/Abstract.lean:66
/-- One operation: the new state and the main cost of the dictionary model(`1 + depth` of the place of the change, plus rotations). An insertionrebuilds the deepest violating subtree when the new leaf is deeper than`log_{1/α} N`; a deletion rebuilds the whole tree when fewer than `α N` keysremain. -/def step (α : ℚ) (s : State) : Dictionary.Op → State × Nat  | .access x => (s, s.1.depth x + 1)  | .insert k =>      let t₁ := Tree.insertAt s.1 k      let N := max s.2 (s.1.size + 1)      let d := t₁.depth k      if α ^ d * N < 1 then        match fix α t₁ k with        | some p => ((p.1, N), d + 1 + p.2)        | none => ((t₁, N), d + 1)      else ((t₁, N), d + 1)  | .delete x =>      let t₁ := bstDelete s.1 x      let c := s.1.depth (deleteTarget s.1 x) + 1      if (t₁.size : ℚ) < α * s.2 then (((rebuild t₁).1, t₁.size), c + (rebuild t₁).2)      else ((t₁, s.2), c)
defClassical.Scapegoat.runpropext · Classical.choice · Quot.soundClassical/Scapegoat/Definitions/Abstract.lean:88
/-- Run a sequence of operations, returning the final state and total cost. -/def run (α : ℚ) (s : State) : List Dictionary.Op → State × Nat  | [] => (s, 0)  | op :: ops =>      let r := step α s op      let q := run α r.1 ops      (q.1, r.2 + q.2)

Violates α t k says that the node of rank k lies at depth dd in t with αd ∣t∣<1\alpha^d\,|t| < 1: the subtree t is too tall for its size. The instance makes the test decidable, so that fix can evaluate it. fix α t k rebuilds the deepest such subtree on the search path to k. Galperin and Rivest define the scapegoat by weight balance, and also discuss a test by height; the library uses a height condition, which yields the same depth bound. step returns the new state and the main cost of the dictionary model: one plus the depth of the place of the change, plus the rotations of the rebuilding. The parameter is a rational number, so that step and run can be evaluated.

Theorem (scapegoat trees are dictionary algorithms). Every valid operation is a dictionary step with the reported cost and no data edits, and every valid run is a dictionary execution.

theoremClassical.Scapegoat.Results.step_dictionarypropext · Classical.choice · Quot.soundClassical/Scapegoat/Abstract.lean:16
/-- Every operation is a dictionary step, with no data edits. -/theorem step_dictionary (α : ℚ) (s : State) (op : Op) (valid : op.Valid s.1.size) :    Dictionary.Step s.1.unit op (step α s op).1.1.unit (step α s op).2 0 :=  Scapegoat.step_dictionary s op valid
theoremClassical.Scapegoat.Results.run_executionpropext · Classical.choice · Quot.soundClassical/Scapegoat/Abstract.lean:21
/-- A run is a dictionary execution with the reported cost. -/theorem run_execution (α : ℚ) (s : State) (ops : List Op) (valid : Op.ValidSeq s.1.size ops) :    Dictionary.Execution s.1.unit ops (run α s ops).1.1.unit (run α s ops).2 0 :=  Scapegoat.run_execution s ops valid

Theorem (depth). From the empty tree, after any valid sequence of operations, every key lies at depth at most log⁡1/αn+1\log_{1/\alpha} n + 1.

theoremClassical.Scapegoat.Results.reachable_depthpropext · Classical.choice · Quot.soundClassical/Scapegoat/Abstract.lean:26
/-- **Height.** From the empty tree, every key always lies at depth at most`log_{1/α} n + 1`. -/theorem reachable_depth (α : ℚ) (hα : 1 / 2 < α ∧ α < 1) (ops : List Op)    (valid : Op.ValidSeq 0 ops) (z : Nat) (hz : z < (run α (.nil, 0) ops).1.1.size) :    ((run α (.nil, 0) ops).1.1.depth z : ℝ) ≤ Real.logb (1 / α) (run α (.nil, 0) ops).1.1.size + 1 :=  Scapegoat.reachable_depth hα ops valid z hz

The cost bound is amortized. Its potential has two parts: a multiple of the total imbalance ∑(∣ size(l)−size(r)∣−1)+\sum (|\,\mathrm{size}(l) - \mathrm{size}(r)| - 1)^+ over all nodes, which pays for partial rebuilds, and a multiple of N−nN - n, which pays for the rebuild of the whole tree after deletions.

defClassical.Scapegoat.sizesFromno axiomsClassical/Scapegoat/Definitions/Abstract.lean:96
/-- The key counts before each operation, starting from `n`. -/def sizesFrom : Nat → List Dictionary.Op → List Nat  | _, [] => []  | n, op :: ops => n :: sizesFrom (op.resize n) ops
defClassical.Scapegoat.boundpropext · Classical.choice · Quot.soundClassical/Scapegoat/Definitions/Abstract.lean:101
/-- The amortized cost of one operation on `n` keys:`(2/(2α - 1) + 1)(log_{1/α} n + 2) + 1 + 2α/(1 - α)`. -/noncomputable def bound (α : ℚ) (n : Nat) : ℝ :=  (2 / (2 * (α : ℝ) - 1) + 1) * (Real.logb (1 / α) n + 2) + 1 + 2 * α / (1 - α)

Theorem (amortized cost). From the empty tree, the total cost of a valid sequence of operations is at most ∑ib(ni)\sum_i b(n_i), where nin_i is the number of keys before operation ii and $b(n)=(22α−1+1)(log⁡1/αn+2)+1+2α1−α.b(n) = \Bigl(\frac{2}{2\alpha - 1} + 1\Bigr)\bigl(\log_{1/\alpha} n + 2\bigr) + 1 + \frac{2\alpha}{1 - \alpha}.$ In particular mm operations cost at most m b(m)m\,b(m).

theoremClassical.Scapegoat.Results.total_costpropext · Classical.choice · Quot.soundClassical/Scapegoat/Abstract.lean:33
/-- **Amortized cost.** From the empty tree, the total cost, rebuildingincluded, is at most `∑ bound α nᵢ` over the key counts `nᵢ` met by theoperations: `O(log n)` per operation. -/theorem total_cost (α : ℚ) (hα : 1 / 2 < α ∧ α < 1) (ops : List Op) (valid : Op.ValidSeq 0 ops) :    ((run α (.nil, 0) ops).2 : ℝ) ≤ ((sizesFrom 0 ops).map (bound α)).sum :=  Scapegoat.total_cost hα ops valid
theoremClassical.Scapegoat.Results.total_cost_lepropext · Classical.choice · Quot.soundClassical/Scapegoat/Abstract.lean:40
/-- In particular `m` operations from the empty tree cost `O(m log m)`. -/theorem total_cost_le (α : ℚ) (hα : 1 / 2 < α ∧ α < 1) (ops : List Op) (valid : Op.ValidSeq 0 ops) :    ((run α (.nil, 0) ops).2 : ℝ) ≤ ops.length * bound α ops.length :=  Scapegoat.total_cost_le hα ops valid

The state includes NN, which is not stored in the tree, so the algorithm is stated as a function on states rather than as a Dictionary.Algorithm. The scapegoat search compares depths with subtree sizes; computing those sizes is not charged, since the model counts search paths and rotations only.

21.4 Restoring by rotations: BB[α] trees

Nievergelt and Reingold (1973) introduced trees of bounded balance, BB[α]. They keep the invariant above with β=1−α\beta = 1 - \alpha, and repair a node whose balance is violated by a single or double rotation at that node. Blum and Mehlhorn (1980) gave the correct range of the parameter for this repair to work, 211<α≤1−22\frac{2}{11} < \alpha \le 1 - \frac{\sqrt 2}{2}. They also proved that rebalancing then needs only O(1)O(1) amortized rotations per update. The rotations at a node of weight ss are rare: they happen only after Ω(s)\Omega(s) updates below it.

Not yet formalized
  • In the parameter range above, single and double rotations restore the invariant after an insertion or a deletion.
  • Rebalancing uses O(1)O(1) amortized rotations per update.
  • The common lemma: a balanced subtree of weight ss needs Ω((β−12)s)\Omega((\beta - \frac12)s) updates before it violates the invariant.

The height bound for BB[α] trees is the theorem above, with β=1−α\beta = 1 - \alpha. Roadmap entry 8.

21.5 Further results

Partial rebuilding is a general technique for making static structures dynamic (Overmars 1983). The weight-balanced trees of Adams (1993), the basis of the ordered sets in Haskell’s containers library and in Mathlib’s Ordnode, are a variant of BB[α] trees with integer parameters.