Chapter 4Putting the keys back
The first three chapters worked entirely with shapes, where a node’s key is its inorder rank. This chapter proves that nothing was lost. A shape on nodes is the same thing as a BST on any fixed list of keys. Rotations, root accesses and whole executions on shapes are exactly the corresponding operations on labelled trees, with the same costs. The local “left smaller, right larger” invariant is equivalent to the inorder formulation used throughout. Finally, the shape type is Mathlib’s BinaryTree Unit under another name.
This is the chapter that justifies the library’s main simplification. Every later theorem is about shapes and ranks; the results below say that each one is equally a theorem about ordinary BSTs on any set of distinct keys, with identical costs.
Fix a list of keys.
- If the keys are strictly increasing (in any preordered type), then for every tree shape with nodes there is exactly one labelled tree with that shape whose inorder traversal is the list, and it satisfies the textbook search-tree invariant: at every node, all keys on the left are smaller and all keys on the right are larger.
- If the keys are distinct (no order needed), let and be labelled trees whose inorder traversals are the list, and let be a sequence of positions in the list. Then an execution serves the keys at positions from to with exactly rotations if and only if an execution serves the ranks from the shape of to the shape of with exactly rotations.
In Lean, a labelled tree is a LabelledTree, its shape is erase, the invariant is LabelledTree.Ordered, and the two kinds of execution are Execution and LabelledTree.Execution.
The Lean statements
/-- Every shape represents exactly one BST on a prescribed increasing key list. -/theorem ordered_labels_exist_unique (shape : Tree) (keys : List α) (length : keys.length = shape.size) (increasing : keys.Pairwise (· < ·)) : ∃! t : LabelledTree α, t.erase = shape ∧ t.inorder = keys ∧ t.Ordered := … OrderingBridge.exists_unique shape keys length increasing/-- Whole request sequences translate between ranks and arbitrary distinct keys.The finite index type makes every requested key valid; costs and endpoints agree. -/theorem execution_on_keys_iff (keys : List α) (distinct : keys.Nodup) (xs : List (Fin keys.length)) (s t : LabelledTree α) (hs : s.inorder = keys) (ht : t.inorder = keys) (k : Nat) : Execution s.erase (xs.map Fin.val) t.erase k ↔ LabelledTree.Execution s (xs.map keys.get) t k := … Bridge.execution_on_keys_iff keys distinct xs s t hs ht kModels.RotationAll theorems here are in Models/Labelled/Abstract.lean, Models/Labelled/Ordering/Abstract.lean and Models/Labelled/Mathlib/Abstract.lean. Their statements mention only the model definitions of Chapter 1 and Chapter 2, the labelled counterparts introduced next, and three small definitions in this chapter.
4.1 Shapes and canonical labels
4.1.1 Labelled rotations, accesses and executions
Models/Rotation/Abstract.lean defines the labelled versions of the three relations of Chapter 2 and Chapter 3, transcribed constructor by constructor. They are the textbook notions, stated for keys of an arbitrary type α.
/-- Ordinary rotations carry node labels with the nodes. -/inductive LabelledTree.Rotate {α : Type} : LabelledTree α → LabelledTree α → Prop where | right {a : LabelledTree α} {x : α} {b : LabelledTree α} {y : α} {c : LabelledTree α} : Rotate (.node (.node a x b) y c) (.node a x (.node b y c)) | left {a : LabelledTree α} {x : α} {b : LabelledTree α} {y : α} {c : LabelledTree α} : Rotate (.node a x (.node b y c)) (.node (.node a x b) y c) | inLeft {a b : LabelledTree α} {x : α} {c : LabelledTree α} : Rotate a b → Rotate (.node a x c) (.node b x c) | inRight {a b c : LabelledTree α} {x : α} : Rotate a b → Rotate (.node c x a) (.node c x b)The four constructors mirror Rotate exactly, with the two keys involved now visible. In right, the left child x of the root y is promoted: (a x b) y c becomes a x (b y c). Every key moves with its node. Nothing in the definition mentions an order on α. A rotation is a purely structural operation, and the fact that it preserves BST order is a theorem (Section 4.2).
/-- Exactly `k` ordinary, label-preserving rotations. -/inductive LabelledTree.Rotations {α : Type} : LabelledTree α → LabelledTree α → Nat → Prop where | refl {t : LabelledTree α} : Rotations t t 0 | step {s t u : LabelledTree α} {k : Nat} : LabelledTree.Rotate s t → Rotations t u k → Rotations s u (k + 1)/-- A labelled root access, with the same rotation-only cost convention. -/def LabelledTree.Access {α : Type} (s t : LabelledTree α) (x : α) (k : Nat) : Prop := LabelledTree.Rotations s t k ∧ match t with | .nil => False | .node _ y _ => y = x/-- An ordinary labelled search sequence, with the same root-access convention. -/inductive LabelledTree.Execution {α : Type} : LabelledTree α → List α → LabelledTree α → Nat → Prop where | nil {t : LabelledTree α} : Execution t [] t 0 | cons {s t : LabelledTree α} {x : α} {k : Nat} {xs : List α} {u : LabelledTree α} {m : Nat} : LabelledTree.Access s t x k → Execution t xs u m → Execution s (x :: xs) u (k + m)These are copies of Rotations, Access and Execution with one change: an access for key x ends with a root whose label is x (y = x), instead of a root whose left subtree has size x. The cost convention is unchanged: rotations only, at any depth.
If α has repeated keys, LabelledTree.Access s t x k is satisfied by bringing any node labelled x to the root. This is why the arbitrary-key correspondence below assumes distinct keys (Nodup). For the canonical labels 0, 1, … the keys are always distinct.
4.1.2 Labelling is a bijection
The first three theorems say that Tree.labelFrom and LabelledTree.erase are inverse to each other on BSTs with consecutive keys.
Theorem (canonical labels). For every shape and offset : labelling with in inorder and then erasing the labels gives back ; the labels read in inorder; and every labelled tree whose inorder traversal is is the canonical labelling of its own shape.
/-- Forgetting the canonical labels recovers the original shape. -/theorem erase_label (t : Tree) (lo : Nat) : (t.labelFrom lo).erase = t := Bridge.erase_label t loModels.Rotation/-- The canonical labels are exactly the keys `lo, …, lo + size - 1`, in order. -/theorem inorder_label (t : Tree) (lo : Nat) : (t.labelFrom lo).inorder = List.range' lo t.size := Bridge.inorder_label t loModels.Rotation/-- Every BST on these consecutive keys is recovered from its shape.Together with `erase_label`, this gives both directions of the correspondence. -/theorem reconstruct (t : LabelledTree Nat) (lo : Nat) (h : t.inorder = List.range' lo t.erase.size) : t.erase.labelFrom lo = t := Bridge.reconstruct t lo hModels.Rotationerase_label: labelling a shape and forgetting the labels returns the shape.inorder_label: the canonical labels readlo, lo+1, …, lo + t.size - 1in inorder.List.range' lo nis the list of thenconsecutive naturals starting atlo.reconstruct: conversely, a labelled tree whose inorder traversal islo, …, lo + n - 1(withnthe size of its own shape) is the canonical labelling of that shape. So every BST on consecutive keys arises from exactly one shape.
The uniqueness half holds for arbitrary keys and does not even need distinctness.
Theorem (labels are unique). Two labelled trees with the same shape and the same inorder list are equal.
/-- More generally, shape and inorder key list uniquely determine a labelled tree. -/theorem labels_unique (s t : LabelledTree α) (shape : s.erase = t.erase) (keys : s.inorder = t.inorder) : s = t := Bridge.ext s t shape keysModels.RotationTwo labelled trees with the same shape and the same inorder list are equal. The shape fixes which node is -th in inorder, and the list fixes its label. Existence for arbitrary key lists is Representation.labels_exist in Section 4.3.
4.1.3 Rotations and accesses correspond exactly
Theorem (rotations correspond). For shapes , and any offset , one rotation turns into if and only if one labelled rotation turns the canonical labelling of into that of . Any labelled rotation, for any labels, leaves the inorder list unchanged.
/-- A shape rotation is exactly a labelled rotation under canonical labelling. -/theorem rotation_iff (s t : Tree) (lo : Nat) : Rotate s t ↔ LabelledTree.Rotate (s.labelFrom lo) (t.labelFrom lo) := Bridge.rotation_iff s t loModels.Rotation/-- Rotations preserve every key and its inorder position, even with arbitrary labels. -/theorem rotation_preserves_keys (h : LabelledTree.Rotate s t) : s.inorder = t.inorder := Bridge.inorder_rotate hModels.Rotationrotation_iff says that one shape rotation is exactly one labelled rotation between the canonically labelled trees, for every offset lo. As stated, it only concerns labelled rotations whose target is canonically labelled. It covers all of them, because every labelled rotation preserves the inorder list (rotation_preserves_keys, stated for arbitrary labels with no order or distinctness hypothesis). A labelled rotation from s.labelFrom lo therefore ends at a tree whose labels are still lo, lo+1, … in inorder, which by reconstruct is t.labelFrom lo for its own shape t.
Theorem (sequences and accesses correspond). For shapes , , exactly rotations turn into if and only if exactly labelled rotations turn the canonical labelling of into that of . Likewise, rotations access rank in and end at if and only if labelled rotations access key in labelled by , and end at labelled the same way.
/-- Whole rotation traces correspond with exactly the same cost. -/theorem rotations_iff (s t : Tree) (k lo : Nat) : Rotations s t k ↔ LabelledTree.Rotations (s.labelFrom lo) (t.labelFrom lo) k := Bridge.rotations_iff s t k loModels.Rotation/-- Accessing implicit rank `x` is exactly accessing explicit key `x` afterlabelling by `0, …, size - 1`, with no change to the number of rotations. -/theorem access_iff (s t : Tree) (x k : Nat) : Access s t x k ↔ LabelledTree.Access (s.labelFrom 0) (t.labelFrom 0) x k := Bridge.access_iff s t x kModels.Rotationrotations_iff lifts the correspondence to traces with the same count k, so costs are preserved exactly, not up to a constant. access_iff is the statement the rotation model relies on: accessing implicit rank x in a shape is exactly accessing the explicit key x in its labelling by 0, …, size − 1, with the same final tree and the same number of rotations. It is stated with offset 0, because the requested rank is an absolute position in the whole tree.
The figure runs the shape model with the ranks displayed as words. Each rotation is a shape rotation, and the inorder list in the panel never changes.
4.2 The textbook invariant
So far “BST” has meant “labelled tree with a prescribed sorted inorder list”. The textbook definition is local instead: at every node, keys in the left subtree are smaller and keys in the right subtree are larger. Models/Labelled/Ordering/Definitions/Abstract.lean states it in that form:
/-- The usual local BST invariant: both children are BSTs, every key on theleft is smaller than the root, and every key on the right is larger. -/def Ordered {α : Type} [LT α] : LabelledTree α → Prop | .nil => True | .node l x r => l.Ordered ∧ r.Ordered ∧ (∀ y ∈ l.inorder, y < x) ∧ (∀ y ∈ r.inorder, x < y)Both subtrees are ordered, every key in l is below the root key x, and every key in r is above it. The quantifiers range over all keys of each subtree (via inorder, used here only as the list of keys), not just over the children. A condition on children alone would be the classic incorrect definition. The relation < comes from any LT α instance, and only the theorems below assume more.
Theorem (local and inorder invariants agree). Over a preordered key type, a labelled tree satisfies the local search-tree invariant if and only if its inorder list is strictly increasing.
/-- Local left/root/right inequalities are equivalent to increasing inorder traversal. -/theorem ordered_iff (t : LabelledTree α) : t.Ordered ↔ t.inorder.Pairwise (· < ·) := OrderingBridge.ordered_iff tWith a preorder on α, the local invariant is equivalent to the inorder list being strictly increasing: List.Pairwise (· < ·) requires a < b for every pair of positions, earlier before later. Strictness makes keys pairwise distinct, since a < a is impossible in a preorder.
Theorem (one BST per shape). Over a preordered key type, let be a shape with nodes and let the list of keys be strictly increasing of length . Then exactly one labelled tree has shape , has that inorder list, and satisfies the search-tree invariant.
/-- Every shape represents exactly one BST on a prescribed increasing key list. -/theorem ordered_labels_exist_unique (shape : Tree) (keys : List α) (length : keys.length = shape.size) (increasing : keys.Pairwise (· < ·)) : ∃! t : LabelledTree α, t.erase = shape ∧ t.inorder = keys ∧ t.Ordered := OrderingBridge.exists_unique shape keys length increasingThis is the formal version of the opening paragraph of Chapter 1. Given a shape with nodes and a strictly increasing list of keys, there is exactly one (∃!) labelled tree with that shape and that inorder list that satisfies the textbook invariant. By ordered_iff, the Ordered conjunct already follows from the other two. It is included so that the statement is the familiar one, with no reference to inorder lists needed for the meaning of “BST”.
Theorem (order is preserved). The canonical labelling of every shape satisfies the search-tree invariant. If a sequence of labelled rotations turns into , then satisfies the invariant if and only if does.
/-- Canonical consecutive-rank labellings satisfy the textbook invariant. -/theorem ordered_label (t : Tree) (lo : Nat) : (t.labelFrom lo).Ordered := OrderingBridge.ordered_label t lo/-- Every legal rotation trace preserves the invariant in both directions. -/theorem rotations_preserve_order {s t : LabelledTree α} {k : Nat} (rotations : LabelledTree.Rotations s t k) : s.Ordered ↔ t.Ordered := OrderingBridge.ordered_rotations rotationsThe canonical labelling of every shape is a BST in the textbook sense (Nat is ordered as usual). Rotation traces preserve the invariant in both directions: for Rotations s t k, s is ordered exactly when t is. Together with rotations_iff, every shape execution is an execution of ordinary BSTs that never violates the search-tree property, and conversely.
The direction “t.Ordered → s.Ordered” is not a typo. The proof rewrites both sides with ordered_iff and uses that a rotation trace leaves the inorder list unchanged, which gives both directions at once.
4.3 Arbitrary keys
Consecutive ranks are a normalization, but the correspondence does not depend on it. These theorems work for keys of any type α, with no order assumed at all.
Theorem (labels exist). For every shape and every list of keys of any type, some labelled tree has shape and that inorder list.
/-- Any fixed inorder key list labels every shape of the correct size.Together with `labels_unique`, this is a bijection for arbitrary key types.A strictly increasing list specializes it to ordinary ordered BSTs. -/theorem labels_exist (t : Tree) (keys : List α) (length : keys.length = t.size) : ∃ u : LabelledTree α, u.erase = t ∧ u.inorder = keys := Bridge.labels_exist t keys lengthModels.RotationAny list of the right length labels any shape. Together with Representation.labels_unique, labelling a shape t by a fixed list keys with keys.length = t.size is a bijection between shapes of that size and labelled trees with inorder list keys. For a strictly increasing list these are exactly the BSTs on those keys, by Representation.ordered_iff.
Theorem (rotations on arbitrary keys). Let and be labelled trees with the same inorder list. Exactly rotations turn the shape of into the shape of if and only if exactly labelled rotations turn into .
/-- Exact-cost rotation equivalence for any fixed key list, with no integer-labelor ordering assumption hidden in the theorem. -/theorem arbitrary_rotations_iff (s t : LabelledTree α) (keys : s.inorder = t.inorder) : Rotations s.erase t.erase k ↔ LabelledTree.Rotations s t k := Bridge.arbitrary_rotations_iff s t keysModels.RotationFor two labelled trees with the same inorder list, a trace between their shapes is exactly a labelled trace between them, with the same count. The hypothesis keys : s.inorder = t.inorder is needed for the backward direction: a shape trace says nothing about labels, so the labels of t must already be the ones a rotation trace would carry over from s.
Theorem (accesses on arbitrary keys). Let and be labelled trees with the same inorder list of distinct keys, and let be a valid position in it. Then rotations access rank in the shape of and end at the shape of if and only if labelled rotations access the -th key of and end at .
/-- Distinct arbitrary keys identify the same accesses as their inorder ranks,with exactly the same rotation count. Strictly ordered key sets are a special case. -/theorem arbitrary_access_iff (s t : LabelledTree α) (keys : s.inorder = t.inorder) (distinct : s.inorder.Nodup) (x k : Nat) (valid : x < s.inorder.length) : Access s.erase t.erase x k ↔ LabelledTree.Access s t s.inorder[x] k := Bridge.arbitrary_access_iff s t keys distinct x k validModels.RotationThis translates rank requests into key requests. Accessing rank x in the shape is the same as accessing the key s.inorder[x], the -th key in inorder, in the labelled tree, at the same cost. There are three hypotheses:
keys: both trees carry the same key list, as above.distinct: the keys are pairwise distinct. Without it, the labelled access could be served by another node with the same label, which is not the node of rankx(see the check box in Section 4.1).valid:xis in range. In Lean,s.inorder[x]needs a proof ofx < s.inorder.lengthto typecheck, andvalidsupplies it.
Theorem (executions on arbitrary keys). Let keys be a list of distinct keys, let and be labelled trees whose inorder lists are keys, and let be a sequence of positions in keys. An execution serves the ranks from the shape of to the shape of with exactly rotations if and only if a labelled execution serves the keys at positions from to with exactly rotations.
/-- Whole request sequences translate between ranks and arbitrary distinct keys.The finite index type makes every requested key valid; costs and endpoints agree. -/theorem execution_on_keys_iff (keys : List α) (distinct : keys.Nodup) (xs : List (Fin keys.length)) (s t : LabelledTree α) (hs : s.inorder = keys) (ht : t.inorder = keys) (k : Nat) : Execution s.erase (xs.map Fin.val) t.erase k ↔ LabelledTree.Execution s (xs.map keys.get) t k := Bridge.execution_on_keys_iff keys distinct xs s t hs ht kModels.RotationThe same for whole request sequences. Requests are elements of Fin keys.length, indices into the key list, so every request is valid by construction. The shape execution serves their values as ranks (xs.map Fin.val), and the labelled execution serves the corresponding keys (xs.map keys.get, where keys.get i is the i-th key). Both endpoints must carry the list keys (hs, ht). The two executions then have the same endpoints, up to erasing labels, and exactly the same cost k.
Any theorem about request sequences over ranks, such as the splay bounds of Section 24.2, transfers to BSTs over any set of distinct keys with no loss: rename the keys to their ranks, apply the theorem, and translate back with execution_on_keys_iff.
4.4 Mathlib’s binary trees
Mathlib’s BinaryTree α stores a value of type α at every node. With α = Unit a node stores nothing, which is exactly a shape. The library provides the two obvious conversions:
/-- The elementary shape as Mathlib's standard binary tree with unit labels. -/def toBinaryTree : Tree → BinaryTree Unit | .nil => .nil | .node l r => .node () (toBinaryTree l) (toBinaryTree r)def fromBinaryTree : BinaryTree Unit → Tree | .nil => .nil | .node _ l r => .node (fromBinaryTree l) (fromBinaryTree r)Mathlib’s node takes the stored value first (.node () l r), and the library’s node takes only the subtrees.
Theorem (shapes are Mathlib’s unit-labelled binary trees). The two conversions are mutually inverse, and the number of nodes of a converted shape is its size.
theorem from_toBinaryTree (t : Tree) : fromBinaryTree (toBinaryTree t) = t := MathlibBridge.from_to ttheorem to_fromBinaryTree (t : BinaryTree Unit) : toBinaryTree (fromBinaryTree t) = t := MathlibBridge.to_from tdef binaryTreeEquiv : Tree ≃ BinaryTree Unit where toFun := toBinaryTree invFun := fromBinaryTree left_inv := from_toBinaryTree right_inv := to_fromBinaryTreetheorem numNodes_toBinaryTree (t : Tree) : (toBinaryTree t).numNodes = t.size := MathlibBridge.numNodes tThe two round trips are identities, so the conversions are packaged as an equivalence Tree ≃ BinaryTree Unit (Mathlib’s type of bijections with explicit inverses). Size corresponds to Mathlib’s numNodes. Anything Mathlib proves about binary trees, such as counting results, therefore applies to shapes through binaryTreeEquiv. The library keeps its own Tree type so that the model files depend only on Lean’s standard library.