Chapter 1Trees without keys
Fix keys . A binary search tree on these keys has no freedom in where the keys go once its shape is fixed: an inorder traversal must read in that order, so the -th node visited holds . Conversely, writing into any -node shape in inorder gives a valid BST. Forgetting the keys and writing them back are inverse operations.
The library therefore represents a BST by its shape alone. The key of a node is its inorder rank, a number in that the tree does not store but can always compute. This removes the search-tree invariant from every definition: there is no ordering condition to state, maintain or prove preserved. No BST and no access sequence is lost, as Chapter 4 proves.
This chapter has no theorems. It introduces the two definitions that every later statement rests on, the shape type Tree and its size Tree.size, and shows how a node’s key is recovered from the shape. It also introduces the ordinary keyed trees, which Chapter 4 uses to show that working with shapes loses nothing. If you are only checking a result, the first two sections are the part you need.
1.1 Shapes
A Tree is either empty (nil) or a node with a left and a right subtree. Nothing else is stored: no key, no size field, no parent pointer, no balance information. Every finite binary tree shape is exactly one value of this type, and two values are equal exactly when the shapes are.
The deriving clause asks Lean to generate a decision procedure for equality (DecidableEq) and a printer (Repr). Neither adds any mathematical content.
Only nodes represent keys. nil is an empty subtree, the “external node” of some textbooks. It is where an unsuccessful search ends and where an insertion puts the new key.
1.2 Size
Tree.size counts nodes, that is, keys. A nil contributes nothing. The two summands and r.size are written in inorder order (left, root, right), which matches how ranks are assigned below.
Lean’s Nat is the type of natural numbers, with truncated subtraction: . The library uses subtraction only on branches where it cannot truncate, as in the search below.
1.3 Depth
The depth of a key is the length of its search path, which is what a search pays in a tree that never changes:
/-- Number of edges on the search path to rank `x`. The empty case only makesthe function total; statements about searches require existing ranks. -/def Tree.depth : Tree → Nat → Nat | .nil, _ => 0 | .node l r, x => if x < l.size then depth l x + 1 else if x = l.size then 0 else depth r (x - l.size - 1) + 1t.depth x searches by rank. At node l r, the root has rank l.size. A smaller x continues in l with the same rank, and a larger one in r with rank x - l.size - 1; that subtraction is only evaluated when x > l.size, so it never truncates. Each step down adds one. On nil the result is ; this case only makes the function total and is never reached for ranks below t.size. Fixed-tree search costs (Chapter 14) and the split-tree finger bounds (Chapter 33) are stated with it.
1.4 Height
The height of a tree counts the nodes on a longest path from the root down:
/-- The number of nodes on a longest root-to-leaf path (`0` for the emptytree). -/def Tree.height : Tree → Nat | .nil => 0 | .node l r => 1 + max (height l) (height r)The empty tree has height and a single node has height . So the height is one more than the largest depth: every key has . Counting nodes rather than edges makes the empty tree fit without a special case. Balanced trees (Chapter 19), rank-balanced and weight-balanced trees (Chapter 20, Chapter 21) and the reference trees of Tango (Section 26.1) are measured with it.
1.5 Implicit keys
Inorder visits the left subtree, then the root, then the right subtree. So in node l r the root has rank l.size: exactly l.size keys come before it. More generally, take a subtree whose smallest key has rank in the whole tree. Its root has rank l.size, its left subtree starts at , and its right subtree starts at l.size$ + 1$.
A subtree does not know its own offset . The same shape can hold keys in one tree and in another. Library functions that need actual keys (the labelling below, the search in Section 24.1, the potential function in Section 24.2) therefore carry the offset as an extra argument, conventionally named lo, and update it exactly as described here.
The squares in the figure are the nil subtrees. Each sits in an inorder gap: the empty subtree between ranks and is “gap ”, and an -node tree has gaps, numbered . Growing the tree at gap adds a key there and shifts every rank at or after up by one. This is what an insertion does to ranks (Section 24.3).
1.6 Labelled trees
To compare shapes with ordinary BSTs, the library also has the ordinary data structure: trees whose nodes carry keys of an arbitrary type α.
/-- A conventional node-labelled binary tree. Labels may be arbitrary keys. -/inductive LabelledTree (α : Type) where | nil | node (left : LabelledTree α) (key : α) (right : LabelledTree α) deriving DecidableEq, ReprNo order on α is assumed, not even decidable equality. The order enters only when we state that a labelled tree is a search tree (Section 4.2). Two operations connect labelled trees with shapes.
/-- Forget the keys, keeping the entire shape. -/def LabelledTree.erase {α : Type} : LabelledTree α → Tree | .nil => .nil | .node l _ r => .node l.erase r.erase/-- Keys in symmetric (left, root, right) order. A BST on a specified sortedkey list is a labelled tree whose inorder traversal is that list. -/def LabelledTree.inorder {α : Type} : LabelledTree α → List α | .nil => [] | .node l x r => l.inorder ++ x :: r.inordererase forgets every key and keeps the full shape. inorder lists the keys in symmetric order, l.inorder ++ x :: r.inorder. The docstring of inorder states the convention used throughout: a BST on a given sorted key list is a labelled tree whose inorder traversal is that list. This is equivalent to the familiar local condition (“left keys smaller, right keys larger”), and Chapter 4 proves the equivalence.
1.7 Canonical labels
Going back from a shape to a labelled tree means writing in the ranks:
/-- Label a shape by consecutive ranks, starting at `lo`. -/def Tree.labelFrom : Tree → Nat → LabelledTree Nat | .nil, _ => .nil | .node l r, lo => .node (l.labelFrom lo) (lo + l.size) (r.labelFrom (lo + l.size + 1))t.labelFrom lo labels the nodes of t with t.size$ - 1$ in inorder. The equations are exactly the offset arithmetic from above. The root of node l r gets lo + l.size, the left subtree is labelled from lo, and the right subtree from lo + l.size + 1. With lo = 0 this writes the implicit keys explicitly: (t.labelFrom 0).inorder = [0, 1, …, t.size - 1].
Three things should hold, and Chapter 4 proves each of them:
(t.labelFrom lo).erase = t. Labelling does not change the shape (Representation.erase_label).(t.labelFrom lo).inorderis the listlo, lo+1, …, so the labels are the ranks offset bylo(Representation.inorder_label).- Every labelled tree whose inorder traversal is
lo, lo+1, …is the canonical labelling of its own shape (Representation.reconstruct).
Together these say that erase and labelFrom 0 are inverse bijections between -node shapes and BSTs on the keys .
The next two chapters work only with Tree. Accesses are stated in terms of ranks, as in “bring the node of rank to the root”, and labelled trees return in Chapter 4 to show that nothing was lost.