Chapter 20Rank-balanced trees
AVL trees (Adel'son-Vel'skiĭ and Landis 1962) and red-black trees (Bayer 1972; Guibas and Sedgewick 1978) are usually presented as two different structures, with different invariants and different case analyses. Haeupler et al. (2015) showed that both are instances of one framework. Each node stores an integer rank, and an invariant on the rank differences between parents and children replaces both the AVL height condition and the red-black colours. The same framework gives a third structure, the weak AVL or WAVL tree, which combines the best properties of both. This chapter follows that framework: one representation, three rules, and one insertion procedure.
Let be a tree on keys whose nodes carry integer ranks, and count its height in nodes. If the ranks satisfy the AVL rule, the height is at most , where is the golden ratio. If they satisfy the red-black rule, or the WAVL rule, the height is at most .
In Lean, ranked trees are RankBalanced.RankedTree, the rules are RankBalanced.Rule, and Valid rule t says that every node of t satisfies the rule. Heights are Tree.height of the underlying shape t.erase.
The Lean statements
/-- **AVL trees** have height at most `log_φ(n + 1)`, about `1.44 log₂ n`. -/theorem avl_height (t : RankedTree) (h : Valid .avl t) : (height t.erase : ℝ) ≤ Real.logb Real.goldenRatio (t.erase.size + 1) := … RankBalanced.avl_height t h/-- **Red-black trees** have height at most `2 log₂(n + 1)`. -/theorem redBlack_height (t : RankedTree) (h : Valid .redBlack t) : (height t.erase : ℝ) ≤ 2 * Real.logb 2 (t.erase.size + 1) := … RankBalanced.redBlack_height t htheorem wavl_height (t : RankedTree) (h : Valid .wavl t) : (height t.erase : ℝ) ≤ 2 * Real.logb 2 (t.erase.size + 1) := … RankBalanced.wavl_height t hBottom-up insertion into a WAVL tree keeps the WAVL rule, keeps the AVL rule when the tree is an AVL tree, and makes at most two rotations. It is a step of the dictionary model whose cost is one plus the depth of the new leaf plus the rotations. Any insertions into the empty tree change at most ranks in total, and leave a tree of height at most .
In Lean, insertion is RankBalanced.insert, which returns the tree, its number of rotations and its number of rank changes. The dictionary step is Dictionary.Step of Chapter 6, with rank changes as its data edits.
The Lean statements
/-- Insertion is a dictionary step: `1 + depth` of the new leaf plus therotations, and one data edit per rank change. -/theorem insert_step (t : RankedTree) (g : Nat) (hg : g ≤ t.erase.size) : Dictionary.Step t (.insert g) (insert t g).1 ((t.insertAt g 0).erase.depth g + 1 + (insert t g).2.1) (insert t g).2.2 := … RankBalanced.insert_step t g hg/-- Insertion keeps the WAVL rule… -/theorem insert_wavl (t : RankedTree) (g : Nat) (h : Valid .wavl t) : Valid .wavl (insert t g).1 := … RankBalanced.insert_wavl t g h/-- …and the AVL rule (the same procedure is AVL insertion). -/theorem insert_avl (t : RankedTree) (g : Nat) (h : Valid .avl t) : Valid .avl (insert t g).1 := … RankBalanced.insert_avl t g h/-- **At most two rotations** per insertion. -/theorem insert_rotations (t : RankedTree) (g : Nat) (h : Valid .wavl t) : (insert t g).2.1 ≤ 2 := … RankBalanced.insert_rotations t g h/-- **Amortized rank changes**: `m` insertions into the empty tree change at most `7m` ranks. -/theorem insertEdits_empty (gs : List Nat) : insertEdits .nil gs ≤ 7 * gs.length := … RankBalanced.insertEdits_empty gs/-- After `m` insertions into the empty tree the height is at most `log_φ(m + 1)`. -/theorem insertAll_height (gs : List Nat) : (Tree.height (insertAll .nil gs).erase : ℝ) ≤ Real.logb Real.goldenRatio (gs.length + 1) := … RankBalanced.insertAll_height gs20.1 Ranks and rank rules
/-- A tree with an integer rank in each node. -/abbrev RankedTree := LabelledTree Int/-- The rank of the root; `-1` for the empty tree. -/def rank : RankedTree → Int | .nil => -1 | .node _ k _ => kA ranked tree is a labelled tree of Chapter 1 whose labels are integers. Keys remain the inorder ranks of the shape, so a ranked tree has two kinds of rank: the key rank of a node, its position in the inorder, and its balance rank, the integer it stores. In this chapter “rank” means the balance rank. The empty tree has rank .
The rank difference of a child is its parent’s rank minus its own. A node whose two children have rank differences and is an node. The three structures differ only in which rank differences they allow:
/-- The balance rules. -/inductive Rule where | avl | redBlack | wavl deriving DecidableEq, Repr/-- No child of the root has rank difference zero. -/def NoZeroChild : RankedTree → Prop | .nil => True | .node l k r => k - rank l ≠ 0 ∧ k - rank r ≠ 0/-- The rule at one node of rank `k` with children `l` and `r`:* AVL: the node is 1,1 or 1,2;* red-black: rank differences are 0 or 1, and a 0-child has no 0-child;* WAVL: rank differences are 1 or 2, and a leaf has rank 0. -/def Rule.Local : Rule → RankedTree → Int → RankedTree → Prop | .avl, l, k, r => (k - rank l = 1 ∧ k - rank r = 1) ∨ (k - rank l = 1 ∧ k - rank r = 2) ∨ (k - rank l = 2 ∧ k - rank r = 1) | .redBlack, l, k, r => (k - rank l = 0 ∨ k - rank l = 1) ∧ (k - rank r = 0 ∨ k - rank r = 1) ∧ (k - rank l = 0 → NoZeroChild l) ∧ (k - rank r = 0 → NoZeroChild r) | .wavl, l, k, r => (k - rank l = 1 ∨ k - rank l = 2) ∧ (k - rank r = 1 ∨ k - rank r = 2) ∧ (l = .nil → r = .nil → k = 0)/-- Every rank is nonnegative and every node satisfies the rule. -/def Valid (rule : Rule) : RankedTree → Prop | .nil => True | .node l k r => 0 ≤ k ∧ rule.Local l k r ∧ Valid rule l ∧ Valid rule r| Structure | Rank rule | Rank is |
|---|---|---|
| AVL | every node is 1,1 or 1,2 | the height in edges |
| Red-black | every rank difference is 0 or 1, and a 0-child has no 0-child | the black height; a 0-child is a red node |
| WAVL | every rank difference is 1 or 2, and every leaf has rank 0 | at least the height in edges, at most twice it |
Rule.Local rule l k r is the rule at one node of rank k with subtrees l and r. Valid rule t asks it at every node, and asks every rank to be nonnegative. The red-black condition “a 0-child has no 0-child” is NoZeroChild, applied to every child of rank difference .
20.2 Heights
Under each rule a counting argument bounds the rank. The smallest AVL tree of rank has keys, one less than a Fibonacci number. For the red-black and WAVL rules, similar counts show that a tree of height , in nodes, has at least keys. Inverting these counts gives the height bounds.
Theorem (heights). In an AVL tree the rank of the root is its height in edges. AVL trees have height at most , in nodes. Red-black trees have height at most . WAVL trees have rank plus one, and height, at most . Every AVL tree is a WAVL tree.
/-- In an AVL tree a node's rank is its height in edges. -/theorem avl_height_rank (t : RankedTree) (h : Valid .avl t) : (height t.erase : Int) = rank t + 1 := RankBalanced.avl_height_rank t h/-- **AVL trees** have height at most `log_φ(n + 1)`, about `1.44 log₂ n`. -/theorem avl_height (t : RankedTree) (h : Valid .avl t) : (height t.erase : ℝ) ≤ Real.logb Real.goldenRatio (t.erase.size + 1) := RankBalanced.avl_height t h/-- **Red-black trees** have height at most `2 log₂(n + 1)`. -/theorem redBlack_height (t : RankedTree) (h : Valid .redBlack t) : (height t.erase : ℝ) ≤ 2 * Real.logb 2 (t.erase.size + 1) := RankBalanced.redBlack_height t h/-- **WAVL trees** have rank (hence height) at most `2 log₂(n + 1)`. -/theorem wavl_rank (t : RankedTree) (h : Valid .wavl t) : (rank t : ℝ) + 1 ≤ 2 * Real.logb 2 (t.erase.size + 1) := RankBalanced.wavl_rank t htheorem wavl_height (t : RankedTree) (h : Valid .wavl t) : (height t.erase : ℝ) ≤ 2 * Real.logb 2 (t.erase.size + 1) := RankBalanced.wavl_height t h/-- Every AVL tree is a WAVL tree. -/theorem avl_wavl (t : RankedTree) (h : Valid .avl t) : Valid .wavl t := RankBalanced.avl_wavl t hKnuth’s sharper form of the AVL bound is , for the height in nodes. The library proves , with the same leading constant but a weaker additive term; the sharper form is not proved.
20.3 Insertion
An insertion adds a leaf of rank at the gap, with LabelledTree.insertAt of Chapter 6. Its parent may now have a 0-child, which both the AVL and the WAVL rule forbid. Going up, the procedure repairs the parent with one of three moves:
- if the other child is a 1-child, promote the parent, increasing its rank by one, and continue at the grandparent;
- otherwise, if the outer child of the 0-child is a 1-child, make one single rotation, with one demotion, and stop;
- otherwise make a double rotation, two rotations with three rank changes, and stop.
/-- Rebalance a node of rank `k` whose left subtree became `l'`. -/def fixLeft (l' : RankedTree) (k : Int) (r : RankedTree) (a e : Nat) : RankedTree × Nat × Nat := if k - rank l' ≠ 0 then (.node l' k r, a, e) else if k - rank r = 1 then (.node l' (k + 1) r, a, e + 1) else match l' with | .node x kx y => if kx - rank x = 1 then (.node x kx (.node y (k - 1) r), a + 1, e + 1) else match y with | .node y₁ _ y₂ => (.node (.node x (k - 1) y₁) k (.node y₂ (k - 1) r), a + 2, e + 3) | .nil => (.node l' k r, a, e) | .nil => (.node l' k r, a, e)/-- Rebalance a node of rank `k` whose right subtree became `r'`. -/def fixRight (l : RankedTree) (k : Int) (r' : RankedTree) (a e : Nat) : RankedTree × Nat × Nat := if k - rank r' ≠ 0 then (.node l k r', a, e) else if k - rank l = 1 then (.node l (k + 1) r', a, e + 1) else match r' with | .node y ky z => if ky - rank z = 1 then (.node (.node l (k - 1) y) ky z, a + 1, e + 1) else match y with | .node y₁ _ y₂ => (.node (.node l (k - 1) y₁) k (.node y₂ (k - 1) z), a + 2, e + 3) | .nil => (.node l k r', a, e) | .nil => (.node l k r', a, e)/-- Insert at gap `g` and rebalance: (tree, rotations, rank changes). -/def insert : RankedTree → Nat → RankedTree × Nat × Nat | .nil, _ => (.node .nil 0 .nil, 0, 0) | .node l k r, g => if g ≤ l.erase.size then let p := insert l g fixLeft p.1 k r p.2.1 p.2.2 else let p := insert r (g - l.erase.size - 1) fixRight l k p.1 p.2.1 p.2.2/-- Insert the gaps of a list one after the other. -/def insertAll (t : RankedTree) : List Nat → RankedTree | [] => t | g :: gs => insertAll (insert t g).1 gs/-- The total number of rank changes of a sequence of insertions. -/def insertEdits (t : RankedTree) : List Nat → Nat | [] => 0 | g :: gs => (insert t g).2.2 + insertEdits (insert t g).1 gsfixLeft l' k r a e repairs a node of rank k whose left subtree became l', adding to the counts a of rotations and e of rank changes; fixRight is its mirror image. insert t g inserts at gap g recursively and repairs on the way back up. insertAll and insertEdits run a list of insertions, and add up their rank changes. The same procedure is AVL insertion: on an AVL tree it produces an AVL tree.
Theorem (insertion). Insertion is a dictionary step whose main cost is one plus the depth of the new leaf, in the tree before rebalancing, plus the rotations, and whose data edits are the rank changes. It adds one key. It keeps the WAVL rule and the AVL rule, and makes at most two rotations.
/-- Insertion is a dictionary step: `1 + depth` of the new leaf plus therotations, and one data edit per rank change. -/theorem insert_step (t : RankedTree) (g : Nat) (hg : g ≤ t.erase.size) : Dictionary.Step t (.insert g) (insert t g).1 ((t.insertAt g 0).erase.depth g + 1 + (insert t g).2.1) (insert t g).2.2 := RankBalanced.insert_step t g hgtheorem insert_size (t : RankedTree) (g : Nat) : (insert t g).1.erase.size = t.erase.size + 1 := RankBalanced.insert_size t g/-- Insertion keeps the WAVL rule… -/theorem insert_wavl (t : RankedTree) (g : Nat) (h : Valid .wavl t) : Valid .wavl (insert t g).1 := RankBalanced.insert_wavl t g h/-- …and the AVL rule (the same procedure is AVL insertion). -/theorem insert_avl (t : RankedTree) (g : Nat) (h : Valid .avl t) : Valid .avl (insert t g).1 := RankBalanced.insert_avl t g h/-- **At most two rotations** per insertion. -/theorem insert_rotations (t : RankedTree) (g : Nat) (h : Valid .wavl t) : (insert t g).2.1 ≤ 2 := RankBalanced.insert_rotations t g hA single insertion may promote all the way up, rank changes. On average it does not. The potential is the number of 1,1 nodes: a promotion turns a 1,1 node into a 1,2 node, and the steps that end the walk create only a constant number of 1,1 nodes.
Theorem (insertions from empty). Any insertions into the empty tree change at most ranks in total, and leave a tree of height at most .
/-- **Amortized rank changes**: `m` insertions into the empty tree change at most `7m` ranks. -/theorem insertEdits_empty (gs : List Nat) : insertEdits .nil gs ≤ 7 * gs.length := RankBalanced.insertEdits_empty gs/-- After `m` insertions into the empty tree the height is at most `log_φ(m + 1)`. -/theorem insertAll_height (gs : List Nat) : (Tree.height (insertAll .nil gs).erase : ℝ) ≤ Real.logb Real.goldenRatio (gs.length + 1) := RankBalanced.insertAll_height gsThe height bound follows from the AVL bound, because insertions alone keep the tree an AVL tree.
20.4 What is not formalized
- Deletion. WAVL deletion with at most two rotations, red-black deletion with at most three, and AVL deletion, which may need rotations.
- Red-black insertion, with at most two rotations.
- Amortized rank changes with deletions: per update for red-black and WAVL trees, and rebalancing at rank exponentially rare in .
- WAVL height with deletions: at most after insertions and any deletions. Without deletions, the theorem above gives .
Roadmap entry 7.
20.5 Further results
Red-black trees are binary encodings of 2-3-4 trees, the B-trees of order 4 (Bayer and McCreight 1972). Several variants simplify their case analysis, among them AA trees (Andersson 1993) and left-leaning red-black trees (Sedgewick 2008). The bibliographic notes of this part give the history, including the worst-case and amortized bounds on rebalancing (Tarjan 1983; Huddleston and Mehlhorn 1982).