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 -balanced, for a constant , when every child’s weight is at most times its parent’s. Along any root-to-leaf path the weight then shrinks by a factor at each step, so the height is at most .
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.
If every child’s weight is at most times its parent’s, for some , then the height, in nodes, is at most . Every tree on keys can be turned into the balanced tree on the same keys by at most 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
/-- **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/-- …by exactly the reported number of rotations… -/theorem rebuild_rotations (t : Tree) : Rotations t (rebuild t).1 (rebuild t).2 := … WeightBalanced.rebuild_rotations t/-- …at most two per key. -/theorem rebuild_cost (t : Tree) : (rebuild t).2 ≤ 2 * t.size := … WeightBalanced.rebuild_cost tFix a rational . 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 . The total cost, rebuilding included, is at most , where is the number of keys before the -th operation and 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
/-- 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/-- **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/-- **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 valid21.1 The invariant
/-- The number of empty leaves: size plus one. -/def weight (t : Tree) : Nat := t.size + 1/-- 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 β rTheorem (height). If a tree is -balanced, for , then its height, in nodes, is at most . The balanced tree on keys is -balanced for every .
/-- **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/-- The balanced tree is `β`-balanced for every `β ≥ 2/3`. -/theorem balanced_balanced (β : ℝ) (hβ : 2 / 3 ≤ β) (n : Nat) : Balanced β (balanced n) := WeightBalanced.balanced_balanced β hβ nThe constant comes from the smallest trees: a root with one child has weights and .
The invariant has one property that a height condition lacks. Suppose a subtree of weight has just been balanced. Then insertions and deletions must happen inside it before it can violate the invariant again. So work proportional to , spent to restore the balance at that node, can be charged to the updates that broke it. Each update lies below nodes, so it is charged 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 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:
/-- 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/-- 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 . It is reached from t by exactly the reported number of rotations, which is at most .
/-- Rebuilding produces the balanced tree on the same keys… -/theorem rebuild_tree (t : Tree) : (rebuild t).1 = balanced t.size := rfl/-- …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/-- …by exactly the reported number of rotations… -/theorem rebuild_rotations (t : Tree) : Rotations t (rebuild t).1 (rebuild t).2 := WeightBalanced.rebuild_rotations t/-- …at most two per key. -/theorem rebuild_cost (t : Tree) : (rebuild t).2 ≤ 2 * t.size := WeightBalanced.rebuild_cost tThe 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.
/-- 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))/-- 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: , the largest number of keys since the last rebuild triggered by a deletion.
- Insertion. If the new leaf lands at depth with , that is , find the deepest subtree on its search path that is too tall for its size, the scapegoat, and rebuild it.
- Deletion. If fewer than keys remain, rebuild the whole tree, and set to the number of keys.
- Access. Search, and change nothing.
/-- 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 < 1instance (α : ℚ) (t : Tree) (k : Nat) : Decidable (Violates α t k) := by unfold Violates; infer_instance/-- 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/-- A scapegoat tree: the shape and the count `N`. -/abbrev State := Tree × Nat/-- 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)/-- 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 in t with : 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.
/-- 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/-- 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 validTheorem (depth). From the empty tree, after any valid sequence of operations, every key lies at depth at most .
/-- **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 hzThe cost bound is amortized. Its potential has two parts: a multiple of the total imbalance over all nodes, which pays for partial rebuilds, and a multiple of , which pays for the rebuild of the whole tree after deletions.
/-- 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/-- 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 , where is the number of keys before operation and $$ In particular operations cost at most .
/-- **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/-- 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 validThe state includes , 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 , 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, . They also proved that rebalancing then needs only amortized rotations per update. The rotations at a node of weight are rare: they happen only after updates below it.
- In the parameter range above, single and double rotations restore the invariant after an insertion or a deletion.
- Rebalancing uses amortized rotations per update.
- The common lemma: a balanced subtree of weight needs updates before it violates the invariant.
The height bound for BB[α] trees is the theorem above, with . 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.