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

Chapter 6Insertions and deletions

Every model so far serves accesses to a fixed set of keys. The classical search trees of Part III are dictionaries. Their main results concern insertions and deletions, and the rebalancing that follows each one. This chapter defines a model for such operations, shared by all of them.

The model keeps the rank view of Chapter 1 and changes three things with respect to the root accesses of Chapter 3:

  • Searches are charged. An operation pays one unit for each node of the search path to the place where it acts, plus one unit per rotation. A search that changes nothing then costs 1+depth(x)1 + \mathrm{depth}(x), exactly the static cost StaticTree.cost of Chapter 14, and nothing forces the key to the root.
  • The key set changes. An insertion names the gap k∈{0,…,n}k \in \{0, \dots, n\} where the new key goes; every rank from kk on then grows by one. A deletion names a rank; every later rank then drops by one.
  • Nodes carry balance data. Rank-balanced trees store an integer rank, red-black trees a colour, BB[α] trees a subtree size, and scapegoat trees nothing at all. Trees with data are the labelled trees of Chapter 1, whose labels are the data, while keys stay inorder ranks. Changing a node’s datum is counted separately from rotations, because the classical results bound the two separately.
Main result
Root accesses are dictionary executions, at cost at most m+2Rm + 2R

Every execution of the rotation model that serves mm requests with RR rotations is also an execution of the dictionary model, serving the same requests as accesses and ending in the same tree, at main cost at most m+2Rm + 2R. In the other direction, searching a tree without changing it is a dictionary execution whose cost is the static search cost ∑j(1+depth(xj))\sum_j (1 + \mathrm{depth}(x_j)).

In Lean, the executions are Execution and Dictionary.Execution, and trees without data become trees with unit data by Tree.unit.

The Lean statements
theoremDictionary.Results.of_executionpropext · Classical.choice · Quot.soundModels/Dictionary/Abstract.lean:46
/-- **The rotation model embeds.** An execution of root accesses with `R`rotations is a dictionary execution of the same accesses with main cost atmost `m + 2R`: the search path to each requested node is paid by therotations that bring it to the root. -/theorem of_execution {s t : Tree} {xs : List Nat} {k : Nat} (h : RotationBST.Execution s xs t k) :    ∃ c, Dictionary.Execution s.unit (xs.map .access) t.unit c 0 ∧ c ≤ xs.length + 2 * k := …  Dictionary.of_execution h
theoremDictionary.Results.static_executionpropext · Quot.soundModels/Dictionary/Abstract.lean:54
/-- Searching without moving costs `∑ (1 + depth x)`, the static search cost(`StaticTree.cost` of the shape). -/theorem static_execution (s : LabelledTree α) (xs : List Nat) (valid : ∀ x ∈ xs, x < s.erase.size) :    Execution s (xs.map .access) s ((xs.map fun x => s.erase.depth x + 1).sum) 0 := …  Dictionary.static_execution s xs valid
18 definitions in 5 chapters · reading list

The bound m+2Rm + 2R holds because each rotation raises the requested key by at most one level, so the search path to it, in the tree before its access, is paid for by the rotations that bring it to the root.

6.1 Operations

inductiveDictionary.Opno axiomsModels/Dictionary/Definitions/Abstract.lean:49
/-- A dictionary operation by rank. -/inductive Op where  | access (x : Nat)  | insert (k : Nat)  | delete (x : Nat)  deriving DecidableEq, Repr
defDictionary.Op.Validno axiomsModels/Dictionary/Definitions/Abstract.lean:56
/-- An operation is valid on `n` keys when its rank exists (its gap, for an insertion). -/def Op.Valid : Op → Nat → Prop  | .access x, n => x < n  | .insert k, n => k ≤ n  | .delete x, n => x < n
defDictionary.Op.resizeno axiomsModels/Dictionary/Definitions/Abstract.lean:62
/-- The number of keys after the operation. -/def Op.resize : Op → Nat → Nat  | .access _, n => n  | .insert _, n => n + 1  | .delete _, n => n - 1
defDictionary.Op.ValidSeqno axiomsModels/Dictionary/Definitions/Abstract.lean:68
/-- Every operation of a sequence is valid on the key count it meets. -/def Op.ValidSeq : Nat → List Op → Prop  | _, [] => True  | n, op :: ops => op.Valid n ∧ Op.ValidSeq (op.resize n) ops

An operation is valid on nn keys when its rank exists, or its gap, for an insertion. resize gives the number of keys after the operation, and ValidSeq n ops checks every operation of a sequence against the number of keys it meets. Split and join, which the splay model of Section 24.3.1 also supports, are not part of this model.

6.2 Moves and structural changes

Between the structural changes, a tree is rearranged by rotations, which carry the data with the nodes (LabelledTree.Rotate, Chapter 4), and by changes of one node’s datum:

inductiveDictionary.Editno axiomsModels/Dictionary/Definitions/Abstract.lean:73
/-- Change the datum of one node. -/inductive Edit {α : Type} : LabelledTree α → LabelledTree α → Prop where  | here {l r : LabelledTree α} {d d' : α} : Edit (.node l d r) (.node l d' r)  | inLeft {a b c : LabelledTree α} {d : α} : Edit a b → Edit (.node a d c) (.node b d c)  | inRight {a b c : LabelledTree α} {d : α} : Edit a b → Edit (.node c d a) (.node c d b)
inductiveDictionary.Movesno axiomsModels/Dictionary/Definitions/Abstract.lean:79
/-- `a` rotations and `e` data edits, in any order. Rotations carry data. -/inductive Moves {α : Type} : LabelledTree α → LabelledTree α → Nat → Nat → Prop where  | refl {t : LabelledTree α} : Moves t t 0 0  | rotate {s t u : LabelledTree α} {a e : Nat} :      LabelledTree.Rotate s t → Moves t u a e → Moves s u (a + 1) e  | edit {s t u : LabelledTree α} {a e : Nat} : Edit s t → Moves t u a e → Moves s u a (e + 1)

Moves s t a e says that a rotations and e data edits, in any order, turn s into t.

An update changes the structure exactly once. Both insertions and deletions use one relation, read in the two directions:

inductiveDictionary.Spliceno axiomsModels/Dictionary/Definitions/Abstract.lean:86
/-- `Splice t x u`: the node of rank `x` in `t` has at most one child, and `u`is `t` with that node removed, its child taking its place. Read backwards, itinserts a node at rank `x` above a subtree or a leaf. -/inductive Splice {α : Type} : LabelledTree α → Nat → LabelledTree α → Prop where  | noLeft {d : α} {r : LabelledTree α} : Splice (.node .nil d r) 0 r  | noRight {l : LabelledTree α} {d : α} : Splice (.node l d .nil) l.erase.size l  | inLeft {l l' r : LabelledTree α} {d : α} {x : Nat} :      Splice l x l' → Splice (.node l d r) x (.node l' d r)  | inRight {l r r' : LabelledTree α} {d : α} {x : Nat} :      Splice r x r' → Splice (.node l d r) (l.erase.size + 1 + x) (.node l d r')
defTree.TwoChildrenno axiomsModels/Dictionary/Definitions/Abstract.lean:18
/-- The node of rank `x` has two nonempty children. -/def Tree.TwoChildren : Tree → Nat → Prop  | .nil, _ => False  | .node l r, x =>      if x < l.size then l.TwoChildren x      else if x = l.size then l ≠ .nil ∧ r ≠ .nil      else r.TwoChildren (x - l.size - 1)

Splice t x u says that the node of rank x in t has at most one child, and that u is t with that node removed, its child taking its place. Read forwards it is a deletion. Read backwards, from u to t, it inserts a node at rank x, either as a new leaf or above an existing subtree. A node with two children cannot be removed directly: the classical deletions remove its predecessor or successor instead, which has at most one child, and keep the node itself. TwoChildren detects that case.

The simplest insertion, with no rebalancing, adds a leaf at the gap:

defTree.insertAtno axiomsModels/Dictionary/Definitions/Abstract.lean:31
/-- Insert a new leaf at gap `g`, so that it gets rank `g`, withoutrebalancing. -/def Tree.insertAt : Tree → Nat → Tree  | .nil, _ => .node .nil .nil  | .node l r, g =>      if g ≤ l.size then .node (insertAt l g) r else .node l (insertAt r (g - l.size - 1))
defLabelledTree.insertAtno axiomsModels/Dictionary/Definitions/Abstract.lean:38
/-- Insert a new leaf with data `a` at gap `g`, without rebalancing. -/def LabelledTree.insertAt {α : Type} : LabelledTree α → Nat → α → LabelledTree α  | .nil, _, a => .node .nil a .nil  | .node l x r, g, a =>      if g ≤ l.erase.size then .node (insertAt l g a) x r      else .node l x (insertAt r (g - l.erase.size - 1) a)
defTree.unitno axiomsModels/Dictionary/Definitions/Abstract.lean:26
/-- A shape with no node data. -/def Tree.unit : Tree → LabelledTree Unit  | .nil => .nil  | .node l r => .node l.unit () r.unit

insertAt t g walks down by comparing the gap with the size of the left subtree, and puts the new node in the empty position it reaches, so that the new node gets rank g. The labelled version takes the new node’s datum as an argument: a rank-balanced tree inserts a node of rank 00. Tree.unit gives a shape unit data, which is how the model treats trees that store nothing.

6.3 Steps and executions

inductiveDictionary.Stepno axiomsModels/Dictionary/Definitions/Abstract.lean:97
/-- One operation from `s` to `t`, with main cost `c` and `e` data edits.* An access to `x` pays `1 + depth x` in `s` and its moves.* An insertion at gap `k` may move, then adds a node at rank `k` (a leaf, or  above a subtree), then moves again. It pays `1 + depth k` of the new node  and its rotations.* A deletion of `x` may move, then splices out the node of rank `x`, or, when  that node has two children, its predecessor or successor (whose datum is  lost while the node at `x` keeps its own), then moves again. It pays  `1 + depth` of the spliced node and its rotations. -/inductive Step {α : Type} : LabelledTree α → Op → LabelledTree α → Nat → Nat → Prop where  | access {s t : LabelledTree α} {x a e : Nat} (valid : x < s.erase.size) :      Moves s t a e → Step s (.access x) t (s.erase.depth x + 1 + a) e  | insert {s u v t : LabelledTree α} {k a₁ e₁ a₂ e₂ : Nat} (valid : k ≤ s.erase.size) :      Moves s u a₁ e₁ → Splice v k u → Moves v t a₂ e₂ →        Step s (.insert k) t (v.erase.depth k + 1 + a₁ + a₂) (e₁ + e₂)  | delete {s u v t : LabelledTree α} {x y a₁ e₁ a₂ e₂ : Nat} (valid : x < s.erase.size)      (target : y = x ∨ (u.erase.TwoChildren x ∧ (y + 1 = x ∨ y = x + 1))) :      Moves s u a₁ e₁ → Splice u y v → Moves v t a₂ e₂ →        Step s (.delete x) t (u.erase.depth y + 1 + a₁ + a₂) (e₁ + e₂)

Step s op t c e is one operation from s to t, with main cost c and e data edits:

  • Access to x: moves only. It pays 1+depth(x)1 + \mathrm{depth}(x) in s, plus its rotations.
  • Insertion at gap k: moves, then the structural change, then moves again. It pays 1+depth1 + \mathrm{depth} of the new node at the moment it is added, plus all rotations.
  • Deletion of x: moves, then a splice of the node of rank x, or of its neighbour x - 1 or x + 1 when the node at x has two children, then moves. It pays 1+depth1 + \mathrm{depth} of the spliced node, plus all rotations. When a neighbour is spliced, the node at x keeps its own datum and the neighbour’s is lost.
Where the search is charged

The search charge is taken in the tree where the structural change happens, not necessarily in the tree before the operation. For the classical trees, which change the structure first and rebalance afterwards, this is the search path in the tree before the operation. An algorithm that rotates first could shorten the path, but each rotation changes a depth by at most one (rotations_depth_reverse below), so the rotations it pays for cover any shortcut. An insertion above an existing subtree pays the path to that subtree, not to the gap below it.

inductiveDictionary.Executionno axiomsModels/Dictionary/Definitions/Abstract.lean:118
/-- A sequence of operations, with total main cost `c` and `e` data edits. -/inductive Execution {α : Type} : LabelledTree α → List Op → LabelledTree α → Nat → Nat → Prop where  | nil {t : LabelledTree α} : Execution t [] t 0 0  | cons {s t u : LabelledTree α} {op : Op} {ops : List Op} {c e c' e' : Nat} :      Step s op t c e → Execution t ops u c' e' → Execution s (op :: ops) u (c + c') (e + e')
structureDictionary.Algorithmno axiomsModels/Dictionary/Definitions/Abstract.lean:124
/-- An online dictionary algorithm. It sees the past operations, the currenttree and the current operation, and returns the new tree with its main costand data edits, certified by a `Step`. -/structure Algorithm (α : Type) where  step : List Op → LabelledTree α → Op → LabelledTree α × Nat × Nat  correct : ∀ past t op, op.Valid t.erase.size →    Step t op (step past t op).1 (step past t op).2.1 (step past t op).2.2
defDictionary.Algorithm.runFromno axiomsModels/Dictionary/Definitions/Abstract.lean:132
/-- Run from a tree, returning the final tree, main cost and data edits. -/def Algorithm.runFrom {α : Type} (A : Algorithm α) (past : List Op) (t : LabelledTree α) :    List Op → LabelledTree α × Nat × Nat  | [] => (t, 0, 0)  | op :: ops =>      let r := A.step past t op      let q := A.runFrom (past ++ [op]) r.1 ops      (q.1, r.2.1 + q.2.1, r.2.2 + q.2.2)

An execution is a sequence of steps, with the costs and edits added up. An online dictionary algorithm sees the past operations, the current tree with its data and the current operation, and returns the new tree with its cost and edits. Its field correct certifies every answer by a Step, so an algorithm cannot under-report its cost.

Theorem (basic properties). An operation changes the number of keys as resize says, only valid operations have steps, and the data do not affect the main cost: forgetting them keeps every step and every execution. An online dictionary algorithm executes every valid sequence.

theoremDictionary.Results.step_sizepropext · Classical.choice · Quot.soundModels/Dictionary/Abstract.lean:16
/-- Operations change the number of keys as expected. -/theorem step_size {s t : LabelledTree α} {op : Op} {c e : Nat} (h : Step s op t c e) :    t.erase.size = op.resize s.erase.size :=  h.size
theoremDictionary.Results.step_validno axiomsModels/Dictionary/Abstract.lean:21
/-- Only valid operations have steps. -/theorem step_valid {s t : LabelledTree α} {op : Op} {c e : Nat} (h : Step s op t c e) :    op.Valid s.erase.size :=  h.valid
theoremDictionary.Results.step_unitpropextModels/Dictionary/Abstract.lean:26
/-- Node data do not affect the main cost: forgetting them keeps every step. -/theorem step_unit {s t : LabelledTree α} {op : Op} {c e : Nat} (h : Step s op t c e) :    Step s.erase.unit op t.erase.unit c 0 :=  h.unit
theoremDictionary.Results.execution_unitpropextModels/Dictionary/Abstract.lean:31
theorem execution_unit {s t : LabelledTree α} {ops : List Op} {c e : Nat}    (h : Execution s ops t c e) : Execution s.erase.unit ops t.erase.unit c 0 :=  h.unit
theoremDictionary.Results.algorithm_executionpropext · Classical.choice · Quot.soundModels/Dictionary/Abstract.lean:35
/-- An online dictionary algorithm executes every valid sequence. -/theorem algorithm_execution (A : Algorithm α) (t : LabelledTree α) (ops : List Op)    (valid : Op.ValidSeq t.erase.size ops) :    Execution t ops (A.runFrom [] t ops).1 (A.runFrom [] t ops).2.1 (A.runFrom [] t ops).2.2 :=  A.runFrom_execution [] t ops valid

6.4 Searches and rotations

Theorem (depth and rotations). If kk rotations turn ss into tt, then every rank’s depth in ss is at most its depth in tt plus kk.

theoremDictionary.Results.rotations_depth_reversepropext · Classical.choice · Quot.soundModels/Dictionary/Abstract.lean:41
/-- Each rotation changes a depth by at most one. -/theorem rotations_depth_reverse {s t : Tree} {k : Nat} (h : Rotations s t k) (x : Nat) :    s.depth x ≤ t.depth x + k :=  h.depth_le_reverse x

This is the fact behind the headline result. In the rotation model, an access to xx ends with xx at the root, at depth 00, so its depth before the access is at most the number of its rotations.

Theorem (the two embeddings). The rotation model embeds, at main cost at most m+2Rm + 2R, and searching without moving costs the static cost.

theoremDictionary.Results.of_executionpropext · Classical.choice · Quot.soundModels/Dictionary/Abstract.lean:46
/-- **The rotation model embeds.** An execution of root accesses with `R`rotations is a dictionary execution of the same accesses with main cost atmost `m + 2R`: the search path to each requested node is paid by therotations that bring it to the root. -/theorem of_execution {s t : Tree} {xs : List Nat} {k : Nat} (h : RotationBST.Execution s xs t k) :    ∃ c, Dictionary.Execution s.unit (xs.map .access) t.unit c 0 ∧ c ≤ xs.length + 2 * k :=  Dictionary.of_execution h
theoremDictionary.Results.static_executionpropext · Quot.soundModels/Dictionary/Abstract.lean:54
/-- Searching without moving costs `∑ (1 + depth x)`, the static search cost(`StaticTree.cost` of the shape). -/theorem static_execution (s : LabelledTree α) (xs : List Nat) (valid : ∀ x ∈ xs, x < s.erase.size) :    Execution s (xs.map .access) s ((xs.map fun x => s.erase.depth x + 1).sum) 0 :=  Dictionary.static_execution s xs valid

6.5 Splay updates as an instance

The splay tree updates of Section 24.3.1 have their own model: a forest of trees, with split and join, and a charge of one unit plus the rotations for every operation. That model stays as it is. These theorems relate it to the dictionary model:

Theorem (splay updates are dictionary steps). A splay access, insertion or deletion is a dictionary step on the same trees, without data, whose main cost is at most 22, 33 and 22 times splay’s own charge.

theoremSplay.Updates.Results.dictionary_accesspropext · Classical.choice · Quot.soundAlgorithms/Splay/Updates/Dictionary/Abstract.lean:14
theorem dictionary_access (t : Tree) (x : Nat) (hx : x < t.size) :    ∃ c, Dictionary.Step t.unit (.access x) (run t x).1.unit c 0 ∧ c ≤ 2 * ((run t x).2 + 1) :=  Updates.dictionary_access t x hx
theoremSplay.Updates.Results.dictionary_insertpropext · Classical.choice · Quot.soundAlgorithms/Splay/Updates/Dictionary/Abstract.lean:18
theorem dictionary_insert (t : Tree) (k : Nat) (hk : k ≤ t.size) :    ∃ c, Dictionary.Step t.unit (.insert k) (insert t k).1.unit c 0 ∧      c ≤ 3 * ((insert t k).2 + 1) :=  Updates.dictionary_insert t k hk
theoremSplay.Updates.Results.dictionary_deletepropext · Classical.choice · Quot.soundAlgorithms/Splay/Updates/Dictionary/Abstract.lean:23
theorem dictionary_delete (t : Tree) (x : Nat) (hx : x < t.size) :    ∃ c, Dictionary.Step t.unit (.delete x) (delete t x).1.unit c 0 ∧      c ≤ 2 * ((delete t x).2 + 1) :=  Updates.dictionary_delete t x hx

The factors come from the search charge: splaying a key rotates once per edge of its search path, so the path is paid for by the rotations. These theorems are about single operations. The amortized bound of Section 24.3.1 is stated in splay’s own forest model, and is not restated in the dictionary model.

The model deliberately stops short of a pointer machine with node allocation. That would be more faithful to an implementation. But the results of Part III are statements about depths, rotations and balance data, and the rank view states them directly.