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 , exactly the static cost
StaticTree.costof Chapter 14, and nothing forces the key to the root. - The key set changes. An insertion names the gap where the new key goes; every rank from 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.
Every execution of the rotation model that serves requests with 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 . In the other direction, searching a tree without changing it is a dictionary execution whose cost is the static search cost .
In Lean, the executions are Execution and Dictionary.Execution, and trees without data become trees with unit data by Tree.unit.
The Lean statements
/-- **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/-- 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 validThe bound 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
/-- A dictionary operation by rank. -/inductive Op where | access (x : Nat) | insert (k : Nat) | delete (x : Nat) deriving DecidableEq, Repr/-- 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/-- The number of keys after the operation. -/def Op.resize : Op → Nat → Nat | .access _, n => n | .insert _, n => n + 1 | .delete _, n => n - 1/-- 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) opsAn operation is valid on 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:
/-- 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)/-- `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:
/-- `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')/-- 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:
/-- 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))/-- 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)/-- A shape with no node data. -/def Tree.unit : Tree → LabelledTree Unit | .nil => .nil | .node l r => .node l.unit () r.unitinsertAt 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 . Tree.unit gives a shape unit data, which is how the model treats trees that store nothing.
6.3 Steps and executions
/-- 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 ins, plus its rotations. - Insertion at gap
k: moves, then the structural change, then moves again. It pays of the new node at the moment it is added, plus all rotations. - Deletion of
x: moves, then a splice of the node of rankx, or of its neighbourx - 1orx + 1when the node atxhas two children, then moves. It pays of the spliced node, plus all rotations. When a neighbour is spliced, the node atxkeeps its own datum and the neighbour’s is lost.
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.
/-- 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')/-- 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/-- 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.
/-- 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/-- 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/-- 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.unittheorem 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/-- 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 valid6.4 Searches and rotations
Theorem (depth and rotations). If rotations turn into , then every rank’s depth in is at most its depth in plus .
/-- 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 xThis is the fact behind the headline result. In the rotation model, an access to ends with at the root, at depth , 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 , and searching without moving costs the static cost.
/-- **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/-- 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 valid6.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 , and times splay’s own charge.
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 hxtheorem 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 hktheorem 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 hxThe 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.