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

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 nn nodes is the same thing as a BST on any fixed list of nn 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.

Main result
Trees on ranks are BSTs on keys, with the same costs

Fix a list of nn keys.

  1. If the keys are strictly increasing (in any preordered type), then for every tree shape with nn 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.
  2. If the keys are distinct (no order needed), let ss and tt be labelled trees whose inorder traversals are the list, and let XX be a sequence of positions in the list. Then an execution serves the keys at positions XX from ss to tt with exactly kk rotations if and only if an execution serves the ranks XX from the shape of ss to the shape of tt with exactly kk 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
theoremRepresentation.ordered_labels_exist_uniquepropext · Quot.soundModels/Labelled/Ordering/Abstract.lean:19
/-- 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
theoremRepresentation.execution_on_keys_iffpropext · Quot.soundModels/Labelled/Abstract.lean:82
/-- 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 k
Statement reads only Models.Rotation
14 definitions in 4 chapters · reading list

All 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 α.

inductiveLabelledTree.Rotateno axiomsModels/Rotation/Abstract.lean:90
/-- 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).

inductiveLabelledTree.Rotationsno axiomsModels/Rotation/Abstract.lean:97
/-- 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)
defLabelledTree.Accessno axiomsModels/Rotation/Abstract.lean:102
/-- 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
inductiveLabelledTree.Executionno axiomsModels/Rotation/Abstract.lean:108
/-- 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.

Reading the Lean

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 tt and offset lolo: labelling tt with lo,lo+1,…lo, lo+1, \dots in inorder and then erasing the labels gives back tt; the labels read lo,…,lo+∣t∣−1lo, \dots, lo + |t| - 1 in inorder; and every labelled tree whose inorder traversal is lo,…,lo+n−1lo, \dots, lo + n - 1 is the canonical labelling of its own shape.

theoremRepresentation.erase_labelpropextModels/Labelled/Abstract.lean:19
/-- Forgetting the canonical labels recovers the original shape. -/theorem erase_label (t : Tree) (lo : Nat) : (t.labelFrom lo).erase = t :=  Bridge.erase_label t lo
Statement reads only Models.Rotation
theoremRepresentation.inorder_labelpropext · Quot.soundModels/Labelled/Abstract.lean:23
/-- 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 lo
Statement reads only Models.Rotation
theoremRepresentation.reconstructpropext · Quot.soundModels/Labelled/Abstract.lean:28
/-- 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 h
Statement reads only Models.Rotation
  • erase_label: labelling a shape and forgetting the labels returns the shape.
  • inorder_label: the canonical labels read lo, lo+1, …, lo + t.size - 1 in inorder. List.range' lo n is the list of the n consecutive naturals starting at lo.
  • reconstruct: conversely, a labelled tree whose inorder traversal is lo, …, lo + n - 1 (with n the 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.

theoremRepresentation.labels_uniquepropextModels/Labelled/Abstract.lean:35
/-- 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 keys
Statement reads only Models.Rotation

Two labelled trees with the same shape and the same inorder list are equal. The shape fixes which node is ii-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 ss, tt and any offset lolo, one rotation turns ss into tt if and only if one labelled rotation turns the canonical labelling of ss into that of tt. Any labelled rotation, for any labels, leaves the inorder list unchanged.

theoremRepresentation.rotation_iffpropext · Quot.soundModels/Labelled/Abstract.lean:40
/-- 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 lo
Statement reads only Models.Rotation
theoremRepresentation.rotation_preserves_keyspropextModels/Labelled/Abstract.lean:45
/-- 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 h
Statement reads only Models.Rotation

rotation_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 ss, tt, exactly kk rotations turn ss into tt if and only if exactly kk labelled rotations turn the canonical labelling of ss into that of tt. Likewise, kk rotations access rank xx in ss and end at tt if and only if kk labelled rotations access key xx in ss labelled by 0,…,∣s∣−10, \dots, |s|-1, and end at tt labelled the same way.

theoremRepresentation.rotations_iffpropext · Quot.soundModels/Labelled/Abstract.lean:50
/-- 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 lo
Statement reads only Models.Rotation
theoremRepresentation.access_iffpropext · Quot.soundModels/Labelled/Abstract.lean:55
/-- 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 k
Statement reads only Models.Rotation

rotations_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:

defLabelledTree.Orderedno axiomsModels/Labelled/Ordering/Definitions/Abstract.lean:9
/-- 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.

theoremRepresentation.ordered_iffpropext · Quot.soundModels/Labelled/Ordering/Abstract.lean:15
/-- Local left/root/right inequalities are equivalent to increasing inorder traversal. -/theorem ordered_iff (t : LabelledTree α) : t.Ordered ↔ t.inorder.Pairwise (· < ·) :=  OrderingBridge.ordered_iff t

With 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 tt be a shape with nn nodes and let the list of keys be strictly increasing of length nn. Then exactly one labelled tree has shape tt, has that inorder list, and satisfies the search-tree invariant.

theoremRepresentation.ordered_labels_exist_uniquepropext · Quot.soundModels/Labelled/Ordering/Abstract.lean:19
/-- 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

This is the formal version of the opening paragraph of Chapter 1. Given a shape with nn nodes and a strictly increasing list of nn 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 ss into tt, then ss satisfies the invariant if and only if tt does.

theoremRepresentation.ordered_labelpropext · Classical.choice · Quot.soundModels/Labelled/Ordering/Abstract.lean:25
/-- Canonical consecutive-rank labellings satisfy the textbook invariant. -/theorem ordered_label (t : Tree) (lo : Nat) : (t.labelFrom lo).Ordered :=  OrderingBridge.ordered_label t lo
theoremRepresentation.rotations_preserve_orderpropext · Quot.soundModels/Labelled/Ordering/Abstract.lean:29
/-- 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 rotations

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

Reading the Lean

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 tt and every list of ∣t∣|t| keys of any type, some labelled tree has shape tt and that inorder list.

theoremRepresentation.labels_existpropext · Quot.soundModels/Labelled/Abstract.lean:61
/-- 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 length
Statement reads only Models.Rotation

Any 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 ss and tt be labelled trees with the same inorder list. Exactly kk rotations turn the shape of ss into the shape of tt if and only if exactly kk labelled rotations turn ss into tt.

theoremRepresentation.arbitrary_rotations_iffpropextModels/Labelled/Abstract.lean:68
/-- 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 keys
Statement reads only Models.Rotation

For 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 ss and tt be labelled trees with the same inorder list of distinct keys, and let xx be a valid position in it. Then kk rotations access rank xx in the shape of ss and end at the shape of tt if and only if kk labelled rotations access the xx-th key of ss and end at tt.

theoremRepresentation.arbitrary_access_iffpropext · Quot.soundModels/Labelled/Abstract.lean:74
/-- 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 valid
Statement reads only Models.Rotation

This translates rank requests into key requests. Accessing rank x in the shape is the same as accessing the key s.inorder[x], the xx-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 rank x (see the check box in Section 4.1).
  • valid: x is in range. In Lean, s.inorder[x] needs a proof of x < s.inorder.length to typecheck, and valid supplies it.

Theorem (executions on arbitrary keys). Let keys be a list of distinct keys, let ss and tt be labelled trees whose inorder lists are keys, and let XX be a sequence of positions in keys. An execution serves the ranks XX from the shape of ss to the shape of tt with exactly kk rotations if and only if a labelled execution serves the keys at positions XX from ss to tt with exactly kk rotations.

theoremRepresentation.execution_on_keys_iffpropext · Quot.soundModels/Labelled/Abstract.lean:82
/-- 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 k
Statement reads only Models.Rotation

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

Consequence

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:

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.

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