Chapter 33Split trees
The online simulation of Section 25.2 keeps groups of keys that were touched at the same time, and it must later break these groups apart, a few keys at a time, as new requests touch parts of them. Each group is a binary search tree in its own right, sitting inside the big tree. What the simulation needs from it is a single operation: split off the keys up to a given rank, paid for by the keys of the group. Over the whole life of a group, a key may be involved in many splits, so a logarithmic cost per split is too much. The cost must be constant per key, amortized over all splits the group ever undergoes.
The classical way to achieve this is a finger search tree in which a split at rank costs , the logarithm of the smaller side. A charge of that form adds up to over any sequence of splits that eventually separates all keys. This accounting is the one used for level-linked search trees in the linear-time Jordan sorting of Hoffmann, Mehlhorn, Rosenstiehl and Tarjan (1986), and Demaine, Harmon, Iacono, Kane and Pătraşcu (2009) build the split trees of their geometric simulation on the same principle. The difficulty in the BST model is that there are no finger pointers. Every access starts at the root, so a finger has to be a shape of the tree: the tree is restructured so that the endpoint is at the root and the keys near it are shallow.
The library implements split trees as 2–3–4 trees viewed as binary search trees. This chapter shows the vocabulary, all in Structures/SplitTree, and the contract that the simulation uses. The implementation of splitting, joining and two-ended fingers is internal to the library; it is checked by Lean but not part of the reading interface.
The chapter’s main result has two halves. A finger at the minimum can be built cheaply as a shape, and from it a key of rank is reached in rotations. Splits charged to their smaller side cost linear time in total.
Let be a 2–3–4 tree of height with keys, stored as a BST in its standard binary representation.
- At most rotations turn that BST into its finger view, a BST on the same keys whose right spine has at most nodes.
- In the finger view, splaying the key of rank is a legal root access that uses at most rotations.
- Separately: take any order of splits that eventually separates keys, and charge for splitting a group into sides of and keys. The total charge is at most .
In Lean, is a SplitTree.Multiway with Multiway.Balanced, its BST is Multiway.binary, the finger view is Finger.binaryView, and the order of splits is a binary tree read by SplitTree.totalCharge.
The Lean statements
/-- Construct the minimum-finger comparison BST using at most three rotationsper key. Attached subtrees keep their inorder positions and internal shapes. -/theorem finger_construction {h : Nat} {t : Multiway} (valid : Multiway.Balanced h t) : Rotations t.binary (Multiway.Finger.binaryView t).tree (Multiway.Finger.viewCost t) ∧ Multiway.Finger.viewCost t ≤ 3 * t.size ∧ (Multiway.Finger.binaryView t).tree.size = t.size ∧ (Multiway.Finger.binaryView t).spine.length ≤ 3 * h := … Multiway.Finger.Binary.Results.construction valid/-- A concrete splay realizes the same bound in rotations. -/theorem finger_access {h : Nat} {t : Multiway} (valid : Multiway.Balanced h t) (rank : Nat) (existsKey : rank < t.size) : Access (Multiway.Finger.binaryView t).tree (Splay.run (Multiway.Finger.binaryView t).tree rank).1 rank (Splay.run (Multiway.Finger.binaryView t).tree rank).2 ∧ (Splay.run (Multiway.Finger.binaryView t).tree rank).2 ≤ 5 * Nat.log2 (rank + 1) + 6 := … Multiway.Finger.Binary.Results.access valid rank existsKey/-- Smaller-side logarithmic charges sum to at most twice the number of keys,for every complete split hierarchy. This is the accounting lemma; a BST splitimplementation and its per-operation bound are separate obligations. -/theorem linear_accounting (hierarchy : Tree) : totalCharge hierarchy ≤ 2 * hierarchy.size := … totalCharge_linear hierarchy33.1 2–3–4 trees without keys
A 2–3–4 tree, the B-tree of order 4 (Bayer and McCreight 1972), has internal nodes with two, three or four children, holding one, two or three keys, and all leaves at the same depth. As with binary shapes in Chapter 1, the library stores no keys. A node’s keys are the inorder ranks between its subtrees.
/-- Unlabelled 2–3–4 trees. Inorder ranks supply the keys, just as for binary BSTs. -/inductive Multiway where | nil | two (left right : Multiway) | three (left middle right : Multiway) | four (first second third fourth : Multiway) deriving DecidableEq, Repr/-- Number of keys, including the one, two, or three keys in each internal node. -/def size : Multiway → Nat | .nil => 0 | .two a b => a.size + b.size + 1 | .three a b c => a.size + b.size + c.size + 2 | .four a b c d => a.size + b.size + c.size + d.size + 3/-- Number of multiway nodes; each merge decreases this reserve. -/def nodes : Multiway → Nat | .nil => 0 | .two a b => a.nodes + b.nodes + 1 | .three a b c => a.nodes + b.nodes + c.nodes + 1 | .four a b c d => a.nodes + b.nodes + c.nodes + d.nodes + 1size counts keys: a node with children contributes keys of its own. nodes counts the multiway nodes. For example, .two (.three .nil .nil .nil) (.two .nil .nil) has keys in the left child, the root key , and key in the right child: size , three nodes.
/-- All external leaves have depth `height`; each internal node has 2–4 children. -/inductive Balanced : Nat → Multiway → Prop | nil : Balanced 0 .nil | two {h : Nat} {a b : Multiway} : Balanced h a → Balanced h b → Balanced (h + 1) (.two a b) | three {h : Nat} {a b c : Multiway} : Balanced h a → Balanced h b → Balanced h c → Balanced (h + 1) (.three a b c) | four {h : Nat} {a b c d : Multiway} : Balanced h a → Balanced h b → Balanced h c → Balanced h d → Balanced (h + 1) (.four a b c d)Balanced h t says that every leaf of t is at depth h. Each constructor requires its subtrees to have the same height, one less than the node’s. The degree bounds are built into the type, so this is the full 2–3–4 invariant. A balanced tree of height has between and keys.
33.2 The binary representation
In the BST model only binary trees exist, so a 2–3–4 tree is an organizing view of a binary search tree. The library fixes one binary representation:
/-- Binary comparison-tree representation. Every attached subtree remains intact. -/def binary : Multiway → Tree | .nil => .nil | .two a b => .node a.binary b.binary | .three a b c => .node a.binary (.node b.binary c.binary) | .four a b c d => .node (.node a.binary b.binary) (.node c.binary d.binary)A 2-node is a binary node. A 3-node is two binary nodes leaning right, with its second key as the right child of its first. A 4-node is three binary nodes in a balanced triangle, with its middle key on top. Rotations, and therefore costs, are always counted on this binary tree; the multiway structure is bookkeeping that tells the algorithm which rotations to perform. The binary tree has the same inorder ranks, so t.binary.size = t.size, and its height is at most twice the multiway height.
The standard top-down repairs of a 2–3–4 tree are local restructurings of a node and its children. Before a split descends into a child that is a 2-node, the child gets an extra key, either borrowed from a sibling or obtained by merging with it:
/-- Give the left 2-node another key by borrowing from its right sibling, ormerge the two children when borrowing is impossible. The second result is theexact binary rotation count; unmatched configurations are unchanged. -/def prepareLeft : Multiway → Multiway × Nat | .two (.two a b) (.two c d) => (.four a b c d, 0) | .two (.two a b) (.three c d e) => (.two (.three a b c) (.two d e), 2) | .two (.two a b) (.four c d e f) => (.two (.three a b c) (.three d e f), 3) | t => (t, 0)/-- Symmetric sibling repair for a right 2-node. -/def prepareRight : Multiway → Multiway × Nat | .two (.two a b) (.two c d) => (.four a b c d, 0) | .two (.three a b c) (.two d e) => (.two (.two a b) (.three c d e), 2) | .two (.four a b c d) (.two e f) => (.two (.three a b c) (.three d e f), 4) | t => (t, 0)Each result pairs the repaired tree with the exact number of binary rotations that turn t.binary into the result’s binary form. Merging two 2-nodes into a 4-node costs nothing: .two (.two a b) (.two c d) and .four a b c d have the same binary representation, so only the multiway reading changes. Borrowing from a 3-node takes two rotations. Borrowing from a 4-node takes three on the left and four on the right, because a 3-node leans right and the mirror image of a repair is not a repair of the mirror image. Patterns that do not match, including a child that is not a 2-node, are left unchanged at cost .
33.3 Contexts
Splitting and finger search move a focus up and down a multiway tree, so the library uses the same device as the pointer machine (Chapter 7): a zipper, the focused subtree together with the path of ancestors, each ancestor recorded with its other children.
/-- One ancestor with a selected child omitted. -/inductive Frame where | twoLeft (right : Multiway) | twoRight (left : Multiway) | threeFirst (middle right : Multiway) | threeMiddle (left right : Multiway) | threeLast (left middle : Multiway) | fourFirst (second third fourth : Multiway) | fourSecond (first third fourth : Multiway) | fourThird (first second fourth : Multiway) | fourLast (first second third : Multiway) deriving DecidableEq, Repr/-- Reattach the focused subtree without changing any sibling. -/def Frame.fill : Frame → Multiway → Multiway | .twoLeft b, t => .two t b | .twoRight a, t => .two a t | .threeFirst b c, t => .three t b c | .threeMiddle a c, t => .three a t c | .threeLast a b, t => .three a b t | .fourFirst b c d, t => .four t b c d | .fourSecond a c d, t => .four a t c d | .fourThird a b d, t => .four a b t d | .fourLast a b c, t => .four a b c tA frame is one ancestor with the focused child omitted. Its constructor names the ancestor’s degree and the position of the hole: threeMiddle a c is a 3-node whose middle child is the focus, with a and c the other two children. fill puts a subtree back into the hole.
/-- Siblings all have the focused subtree's height. -/def Frame.Valid (h : Nat) : Frame → Prop | .twoLeft b => Balanced h b | .twoRight a => Balanced h a | .threeFirst b c => Balanced h b ∧ Balanced h c | .threeMiddle a c => Balanced h a ∧ Balanced h c | .threeLast a b => Balanced h a ∧ Balanced h b | .fourFirst b c d => Balanced h b ∧ Balanced h c ∧ Balanced h d | .fourSecond a c d => Balanced h a ∧ Balanced h c ∧ Balanced h d | .fourThird a b d => Balanced h a ∧ Balanced h b ∧ Balanced h d | .fourLast a b c => Balanced h a ∧ Balanced h b ∧ Balanced h c/-- Reassemble nearest-first ancestors. -/def plug : List Frame → Multiway → Multiway | [], t => t | f :: fs, t => plug fs (f.fill t)/-- Heights increase by one at each enclosing multiway node. -/def Valid : Nat → List Frame → Prop | _, [] => True | h, f :: fs => f.Valid h ∧ Valid (h + 1) fs/-- Perform a computed local edit and reassemble its entire enclosing tree. -/def edit (fs : List Frame) (t : Multiway) (operation : Multiway → Multiway × Nat) : Multiway × Nat := let result := operation t (plug fs result.1, result.2)plug fs t reassembles the whole tree from the focus t and the frames fs, nearest ancestor first, exactly like Pointer.plug for binary trees. Valid h fs says that the result is balanced when the focus has height h: the siblings in the nearest frame have height h, those in the next frame h + 1, and so on. edit applies a local operation such as prepareLeft at the focus, reports its rotation count, and plugs the result back. The rotation count is unchanged by plugging, because a rotation inside a subtree is a rotation of the whole tree (Rotations.inLeft).
33.4 The minimum finger
A finger at the minimum is the path from the leftmost leaf up to the root, read bottom-up. Searching for rank from the finger climbs this path until the subtree reached contains rank , and then descends. The climb is the interesting part:
/-- Nearest-first ancestors of the leftmost external leaf. Each frame retainsits siblings, so the original tree can be reconstructed exactly. -/def leftSpine : Multiway → List Frame | .nil => [] | .two a b => leftSpine a ++ [.twoLeft b] | .three a b c => leftSpine a ++ [.threeFirst b c] | .four a b c d => leftSpine a ++ [.fourFirst b c d]/-- Ascend until the growing leftmost interval contains `rank`. The result isthe number of crossed multiway levels, not a claim about BST rotation cost. -/def ascend : List Frame → Multiway → Nat → Nat | [], _, _ => 0 | f :: fs, focus, rank => if rank < focus.size then 0 else 1 + ascend fs (f.fill focus) rank/-- Number of levels needed to locate a containing ancestor from the minimum. -/def searchLevels (t : Multiway) (rank : Nat) : Nat := ascend (leftSpine t) .nil rankleftSpine t is the context of the leftmost leaf, nearest ancestor first. Each frame keeps all siblings, so nothing is lost. ascend fs focus rank climbs one frame at a time, filling the focus into its parent, and stops as soon as the focus has more than rank keys. The focus is always a prefix of the tree in inorder, because it is the leftmost subtree at its height, so “more than rank keys” means “contains rank rank”. searchLevels t rank starts from the empty leftmost leaf and counts the levels climbed.
The first theorem says that the left spine is a faithful representation of the tree, with one frame per level.
Theorem (the left spine). For a balanced 2–3–4 tree t of height , plugging the empty leaf into its left spine gives back t, the frames are valid from height , and there are exactly of them.
/-- The minimum finger reconstructs the original tree with one frame per level. -/theorem finger_representation {h : Nat} {t : Multiway} (valid : Multiway.Balanced h t) : Multiway.Context.plug (Multiway.Finger.leftSpine t) .nil = t ∧ Multiway.Context.Valid 0 (Multiway.Finger.leftSpine t) ∧ (Multiway.Finger.leftSpine t).length = h := Multiway.Finger.Results.representation validA balanced subtree of height has at least keys, so the climb for rank stops after about levels. Splitting needs the same from both ends, because the cost must depend on the smaller side. The maximum finger is the minimum finger of the mirror image:
/-- Reverse the multiway order to obtain the corresponding maximum finger. -/def mirror : Multiway → Multiway | .nil => .nil | .two a b => .two (mirror b) (mirror a) | .three a b c => .three (mirror c) (mirror b) (mirror a) | .four a b c d => .four (mirror d) (mirror c) (mirror b) (mirror a)/-- Choose the nearer endpoint by rank distance, then ascend from that finger. -/def nearSearchLevels (t : Multiway) (rank : Nat) : Nat := if rank ≤ t.size - 1 - rank then searchLevels t rank else searchLevels (mirror t) (t.size - 1 - rank)mirror reverses every node, so rank becomes rank . nearSearchLevels climbs from whichever endpoint is nearer in rank.
Theorem (climbing from the nearer end). For a balanced 2–3–4 tree with keys and any rank , the number of levels climbed from the nearer endpoint is at most .
/-- Ascending from the nearer endpoint costs logarithmically many multiwaylevels in the smaller side. -/theorem nearer_endpoint {h : Nat} {t : Multiway} (valid : Multiway.Balanced h t) (rank : Nat) : Multiway.Finger.nearSearchLevels t rank ≤ Nat.log2 (min rank (t.size - 1 - rank) + 1) + 1 := Multiway.Finger.Results.nearer_endpoint valid rankThis is the “logarithm of the smaller side” that the accounting below charges for.
nearSearchLevelsand the theorem use truncated subtractiont.size - 1 - rank. Forrank ≥ t.sizeit is , so the theorem says that an out-of-range rank needs at most one level, which is true: the climb from the minimum ends at the root andascendstops when it runs out of frames. No hypothesisrank < t.sizeis needed.- The levels are multiway levels, not BST costs. The next section turns them into BST depth.
33.5 A finger as a binary search tree
In the BST model a finger cannot be a pointer, so the library builds a binary tree whose root is the minimum and in which a key of rank is at depth . Take the left spine of the 2–3–4 tree and turn it into a right spine hanging from the minimum: walking down the new spine visits the separating keys of the old left spine in increasing order, and each separating key carries, as its left subtree, the binary representation of the subtree that lies just before it.
/-- A binary right spine, with each off-spine subtree attached on the left. -/def comb : List Tree → Tree → Tree | [], tail => tail | a :: rest, tail => .node a (comb rest tail)/-- Comparison-tree view of the minimum finger. The retained subtrees appearin their original inorder order; only the spine separators are regrouped. -/structure BinaryView where spine : List Tree tail : Tree deriving DecidableEq, Reprdef BinaryView.tree (v : BinaryView) : Tree := comb v.spine v.taildef binaryView : Multiway → BinaryView | .nil => ⟨[], .nil⟩ | .two a b => let v := binaryView a; ⟨v.spine ++ [v.tail], b.binary⟩ | .three a b c => let v := binaryView a; ⟨v.spine ++ [v.tail, b.binary], c.binary⟩ | .four a b c d => let v := binaryView a; ⟨v.spine ++ [v.tail, b.binary, c.binary], d.binary⟩comb spine tail is the right spine whose -th node has spine[i] as its left subtree, ending in tail. binaryView computes the spine recursively from the left: the view of the leftmost child is extended by one spine node per key of the current node. For a 2-node .two a b, the old tail of a (its subtree to the left of the new key) moves onto the spine, and b.binary becomes the new tail. A 3-node adds two spine nodes and a 4-node three. The deepest left subtree on the spine is the empty leaf below the minimum, so the root of the view has no left child: it is rank .
/-- Exact rotation count for constructing the minimum-finger comparison tree. -/def viewCost : Multiway → Nat | .nil => 0 | .two a _ | .three a _ _ => viewCost a + (binaryView a).spine.length | .four a _ _ _ => viewCost a + 2 * (binaryView a).spine.length + 1viewCost is an exact count of the rotations that turn t.binary into the view, level by level: each level costs one rotation per spine node built so far, and twice as many plus one for a 4-node, whose binary representation has its middle key on top.
The view has four properties that the simulation uses.
Theorem (building the finger). For a balanced 2–3–4 tree t of height with keys, exactly viewCost t rotations take t.binary to the view, and viewCost t is at most . The view has keys, and its right spine has at most nodes.
/-- Construct the minimum-finger comparison BST using at most three rotationsper key. Attached subtrees keep their inorder positions and internal shapes. -/theorem finger_construction {h : Nat} {t : Multiway} (valid : Multiway.Balanced h t) : Rotations t.binary (Multiway.Finger.binaryView t).tree (Multiway.Finger.viewCost t) ∧ Multiway.Finger.viewCost t ≤ 3 * t.size ∧ (Multiway.Finger.binaryView t).tree.size = t.size ∧ (Multiway.Finger.binaryView t).spine.length ≤ 3 * h := Multiway.Finger.Binary.Results.construction validSo creating a finger is linear in the group’s size, which is what the simulation pays when it creates a new group.
Theorem (the minimum is at the root). For every nonempty 2–3–4 tree t, the viewCost t rotations from t.binary to the view form a root access of rank , in the sense of Chapter 3.
/-- The initialized comparison BST exposes the minimum at its root. -/theorem finger_minimum (t : Multiway) (nonempty : t ≠ .nil) : Access t.binary (Multiway.Finger.binaryView t).tree 0 (Multiway.Finger.viewCost t) := Multiway.Finger.Binary.Results.minimum t nonemptyTheorem (search near the minimum). For a balanced 2–3–4 tree t and a rank of t, the key of rank has depth at most in the view.
/-- Ordinary BST search in the minimum finger has logarithmic rank-distance cost. -/theorem finger_search_depth {h : Nat} {t : Multiway} (valid : Multiway.Balanced h t) (rank : Nat) (existsKey : rank < t.size) : Tree.depth (Multiway.Finger.binaryView t).tree rank ≤ 5 * Nat.log2 (rank + 1) + 6 := Multiway.Finger.Binary.Results.search_depth valid rank existsKeyDepth is the search depth Tree.depth of Chapter 1. An ordinary root-to-node search, with no finger pointer, now costs logarithmically in the distance to the minimum.
Theorem (access near the minimum). For a balanced 2–3–4 tree t and a rank of t, splaying rank in the view (Splay.run, Section 24.1) is a legal root access with at most rotations.
/-- A concrete splay realizes the same bound in rotations. -/theorem finger_access {h : Nat} {t : Multiway} (valid : Multiway.Balanced h t) (rank : Nat) (existsKey : rank < t.size) : Access (Multiway.Finger.binaryView t).tree (Splay.run (Multiway.Finger.binaryView t).tree rank).1 rank (Splay.run (Multiway.Finger.binaryView t).tree rank).2 ∧ (Splay.run (Multiway.Finger.binaryView t).tree rank).2 ≤ 5 * Nat.log2 (rank + 1) + 6 := Multiway.Finger.Binary.Results.access valid rank existsKeySplaying a node at depth performs exactly rotations, so this follows from the depth bound.
finger_search_depthandfinger_accessassumeBalanced h tbut their bounds do not mentionh. Roughly, the constant has two sources: the spine grows by up to three nodes per multiway level, and the binary representation of a subtree can be twice as tall as its multiway height.- The statements mention
Tree.depth(from the rotation model) andSplay.run(from the splay algorithm). They are used only to measure the view; split trees do not depend on splaying otherwise.
The figure draws a random balanced 2–3–4 tree and its two binary forms, with every key at the horizontal position of its rank. Select a key to see the levels the finger climbs, and compare its depth in t.binary with its depth in the view. For small ranks the view is much shallower; for ranks near the maximum, switch the finger to “nearer end”.
33.6 Paying for splits
The simulation does not use one split but a whole hierarchy of them. A group of keys is split around some key, then each side is split again, in any interleaving with other work, until every key has been separated. Such a hierarchy is itself a binary tree: its root is the first splitting key, and its subtrees are the hierarchies of the two sides. The charge for one split is the logarithm of the smaller side:
/-- Charge for splitting around one key, with `left` and `right` keys remaining.This measures the smaller-side search term, not an implemented BST operation. -/def charge (left right : Nat) : Nat := 1 + Nat.log2 (min left right + 1)/-- A binary tree records a complete split hierarchy: its root is removed first,then the two resulting intervals are split in arbitrary interleaved order. -/def totalCharge : Tree → Nat | .nil => 0 | .node l r => totalCharge l + totalCharge r + charge l.size r.sizecharge left right is , where left and right are the numbers of keys remaining on each side. totalCharge adds the charges over a hierarchy.
Theorem (linear accounting). For every hierarchy of splits on keys, the total charge is at most .
/-- Smaller-side logarithmic charges sum to at most twice the number of keys,for every complete split hierarchy. This is the accounting lemma; a BST splitimplementation and its per-operation bound are separate obligations. -/theorem linear_accounting (hierarchy : Tree) : totalCharge hierarchy ≤ 2 * hierarchy.size := totalCharge_linear hierarchyThe proof keeps a reserve of for every interval of keys. Splitting an interval of keys into and releases the reserve of the larger interval and creates those of the two smaller ones, and the difference covers the charge, because . The same quantity appears, scaled by a constant number of rotations per unit, as the credit that the simulation stores with each group (Section 25.2.4).
The abstract is a contract, not a split-tree implementation. It states construction, minimum, search and access for a minimum finger, the climb from the nearer endpoint, and the accounting lemma. The BST implementation of splitting, with its per-split rotation bound, the two-ended finger state (a minimum finger and a maximum finger on either side of a median root), joins and rebuilding are proved in internal Results modules under Structures/SplitTree. The simulation relies on them, and their statements are checked by Lean, but they are outside the reading interface, so trusting the simulation’s statement does not require reading them.