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

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.

AVL, red-black and WAVL trees have logarithmic height

Let tt be a tree on nn keys whose nodes carry integer ranks, and count its height in nodes. If the ranks satisfy the AVL rule, the height is at most log⁡φ(n+1)≈1.44log⁡2(n+1)\log_\varphi(n + 1) \approx 1.44 \log_2(n + 1), where φ\varphi is the golden ratio. If they satisfy the red-black rule, or the WAVL rule, the height is at most 2log⁡2(n+1)2\log_2(n + 1).

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
theoremClassical.RankBalanced.Results.avl_heightpropext · Classical.choice · Quot.soundClassical/RankBalanced/Abstract.lean:18
/-- **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
theoremClassical.RankBalanced.Results.redBlack_heightpropext · Classical.choice · Quot.soundClassical/RankBalanced/Abstract.lean:23
/-- **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
theoremClassical.RankBalanced.Results.wavl_heightpropext · Classical.choice · Quot.soundClassical/RankBalanced/Abstract.lean:33
theorem wavl_height (t : RankedTree) (h : Valid .wavl t) :    (height t.erase : ℝ) ≤ 2 * Real.logb 2 (t.erase.size + 1) := …  RankBalanced.wavl_height t h
11 definitions in 2 chapters · reading list
Main result · Haeupler et al. 2015
WAVL and AVL insertion uses at most two rotations, and O(1)O(1) amortized rank changes from the empty tree

Bottom-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 mm insertions into the empty tree change at most 7m7m ranks in total, and leave a tree of height at most log⁡φ(m+1)\log_\varphi(m + 1).

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
theoremClassical.RankBalanced.Results.insert_steppropext · Quot.soundClassical/RankBalanced/Insertion/Abstract.lean:14
/-- 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
theoremClassical.RankBalanced.Results.insert_wavlpropext · Classical.choice · Quot.soundClassical/RankBalanced/Insertion/Abstract.lean:24
/-- 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
theoremClassical.RankBalanced.Results.insert_avlpropext · Classical.choice · Quot.soundClassical/RankBalanced/Insertion/Abstract.lean:28
/-- …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
theoremClassical.RankBalanced.Results.insert_rotationspropext · Classical.choice · Quot.soundClassical/RankBalanced/Insertion/Abstract.lean:32
/-- **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
theoremClassical.RankBalanced.Results.insertEdits_emptypropext · Classical.choice · Quot.soundClassical/RankBalanced/Insertion/Abstract.lean:41
/-- **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
theoremClassical.RankBalanced.Results.insertAll_heightpropext · Classical.choice · Quot.soundClassical/RankBalanced/Insertion/Abstract.lean:36
/-- 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 gs
25 definitions in 4 chapters · reading list

20.1 Ranks and rank rules

defClassical.RankBalanced.RankedTreeno axiomsClassical/RankBalanced/Definitions/Abstract.lean:12
/-- A tree with an integer rank in each node. -/abbrev RankedTree := LabelledTree Int
defClassical.RankBalanced.rankno axiomsClassical/RankBalanced/Definitions/Abstract.lean:15
/-- The rank of the root; `-1` for the empty tree. -/def rank : RankedTree → Int  | .nil => -1  | .node _ k _ => k

A 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 −1-1.

The rank difference of a child is its parent’s rank minus its own. A node whose two children have rank differences ii and jj is an i,ji,j node. The three structures differ only in which rank differences they allow:

inductiveClassical.RankBalanced.Ruleno axiomsClassical/RankBalanced/Definitions/Abstract.lean:20
/-- The balance rules. -/inductive Rule where  | avl  | redBlack  | wavl  deriving DecidableEq, Repr
defClassical.RankBalanced.NoZeroChildno axiomsClassical/RankBalanced/Definitions/Abstract.lean:27
/-- 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
defClassical.RankBalanced.Rule.Localno axiomsClassical/RankBalanced/Definitions/Abstract.lean:32
/-- 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)
defClassical.RankBalanced.Validno axiomsClassical/RankBalanced/Definitions/Abstract.lean:47
/-- 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 00.

20.2 Heights

Under each rule a counting argument bounds the rank. The smallest AVL tree of rank kk has Fk+3−1F_{k+3} - 1 keys, one less than a Fibonacci number. For the red-black and WAVL rules, similar counts show that a tree of height hh, in nodes, has at least 2h/2−12^{h/2} - 1 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 log⁡φ(n+1)\log_\varphi(n + 1), in nodes. Red-black trees have height at most 2log⁡2(n+1)2\log_2(n + 1). WAVL trees have rank plus one, and height, at most 2log⁡2(n+1)2\log_2(n + 1). Every AVL tree is a WAVL tree.

theoremClassical.RankBalanced.Results.avl_height_rankpropext · Classical.choice · Quot.soundClassical/RankBalanced/Abstract.lean:14
/-- 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
theoremClassical.RankBalanced.Results.avl_heightpropext · Classical.choice · Quot.soundClassical/RankBalanced/Abstract.lean:18
/-- **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
theoremClassical.RankBalanced.Results.redBlack_heightpropext · Classical.choice · Quot.soundClassical/RankBalanced/Abstract.lean:23
/-- **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
theoremClassical.RankBalanced.Results.wavl_rankpropext · Classical.choice · Quot.soundClassical/RankBalanced/Abstract.lean:28
/-- **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 h
theoremClassical.RankBalanced.Results.wavl_heightpropext · Classical.choice · Quot.soundClassical/RankBalanced/Abstract.lean:33
theorem wavl_height (t : RankedTree) (h : Valid .wavl t) :    (height t.erase : ℝ) ≤ 2 * Real.logb 2 (t.erase.size + 1) :=  RankBalanced.wavl_height t h
theoremClassical.RankBalanced.Results.avl_wavlpropext · Quot.soundClassical/RankBalanced/Abstract.lean:37
/-- Every AVL tree is a WAVL tree. -/theorem avl_wavl (t : RankedTree) (h : Valid .avl t) : Valid .wavl t :=  RankBalanced.avl_wavl t h

Knuth’s sharper form of the AVL bound is h<1.4405log⁡2(n+2)−0.3277h < 1.4405 \log_2(n + 2) - 0.3277, for the height hh in nodes. The library proves log⁡φ(n+1)\log_\varphi(n + 1), with the same leading constant 1/log⁡2φ≈1.44041/\log_2\varphi \approx 1.4404 but a weaker additive term; the sharper form is not proved.

20.3 Insertion

An insertion adds a leaf of rank 00 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.
defClassical.RankBalanced.fixLeftno axiomsClassical/RankBalanced/Insertion/Definitions/Abstract.lean:15
/-- 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)
defClassical.RankBalanced.fixRightno axiomsClassical/RankBalanced/Insertion/Definitions/Abstract.lean:29
/-- 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)
defClassical.RankBalanced.insertno axiomsClassical/RankBalanced/Insertion/Definitions/Abstract.lean:43
/-- 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
defClassical.RankBalanced.insertAllno axiomsClassical/RankBalanced/Insertion/Definitions/Abstract.lean:54
/-- 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
defClassical.RankBalanced.insertEditsno axiomsClassical/RankBalanced/Insertion/Definitions/Abstract.lean:59
/-- 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 gs

fixLeft 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.

theoremClassical.RankBalanced.Results.insert_steppropext · Quot.soundClassical/RankBalanced/Insertion/Abstract.lean:14
/-- 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
theoremClassical.RankBalanced.Results.insert_sizepropext · Quot.soundClassical/RankBalanced/Insertion/Abstract.lean:21
theorem insert_size (t : RankedTree) (g : Nat) : (insert t g).1.erase.size = t.erase.size + 1 :=  RankBalanced.insert_size t g
theoremClassical.RankBalanced.Results.insert_wavlpropext · Classical.choice · Quot.soundClassical/RankBalanced/Insertion/Abstract.lean:24
/-- 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
theoremClassical.RankBalanced.Results.insert_avlpropext · Classical.choice · Quot.soundClassical/RankBalanced/Insertion/Abstract.lean:28
/-- …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
theoremClassical.RankBalanced.Results.insert_rotationspropext · Classical.choice · Quot.soundClassical/RankBalanced/Insertion/Abstract.lean:32
/-- **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

A single insertion may promote all the way up, Θ(log⁡n)\Theta(\log n) 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 mm insertions into the empty tree change at most 7m7m ranks in total, and leave a tree of height at most log⁡φ(m+1)\log_\varphi(m + 1).

theoremClassical.RankBalanced.Results.insertEdits_emptypropext · Classical.choice · Quot.soundClassical/RankBalanced/Insertion/Abstract.lean:41
/-- **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
theoremClassical.RankBalanced.Results.insertAll_heightpropext · Classical.choice · Quot.soundClassical/RankBalanced/Insertion/Abstract.lean:36
/-- 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 gs

The height bound follows from the AVL bound, because insertions alone keep the tree an AVL tree.

20.4 What is not formalized

Not yet formalized
  • Deletion. WAVL deletion with at most two rotations, red-black deletion with at most three, and AVL deletion, which may need Θ(log⁡n)\Theta(\log n) rotations.
  • Red-black insertion, with at most two rotations.
  • Amortized rank changes with deletions: O(1)O(1) per update for red-black and WAVL trees, and rebalancing at rank kk exponentially rare in kk.
  • WAVL height with deletions: at most log⁡φm\log_\varphi m after mm insertions and any deletions. Without deletions, the theorem above gives log⁡φ(m+1)\log_\varphi(m + 1).

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).