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

Chapter 1Trees without keys

Fix keys k0<k1<⋯<kn−1k_0 < k_1 < \dots < k_{n-1}. 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 k0,…,kn−1k_0, \dots, k_{n-1} in that order, so the ii-th node visited holds kik_i. Conversely, writing k0,…,kn−1k_0, \dots, k_{n-1} into any nn-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 {0,…,n−1}\{0, \dots, n-1\} 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

inductiveTreeno axiomsModels/Rotation/Abstract.lean:12
inductive Tree where  | nil  | node (left right : Tree)  deriving DecidableEq, Repr

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

defTree.sizeno axiomsModels/Rotation/Abstract.lean:17
def Tree.size : Tree → Nat  | .nil => 0  | .node l r => l.size + 1 + r.size

Tree.size counts nodes, that is, keys. A nil contributes nothing. The two summands 11 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: 3−5=03 - 5 = 0. 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:

defTree.depthno axiomsModels/Rotation/Abstract.lean:21
/-- 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) + 1

t.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 00; 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:

defTree.heightno axiomsModels/Rotation/Abstract.lean:30
/-- 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 00 and a single node has height 11. So the height is one more than the largest depth: every key xx has depth(x)<height\mathrm{depth}(x) < \mathrm{height}. 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 lolo in the whole tree. Its root has rank lo+lo + {}l.size, its left subtree starts at lolo, and its right subtree starts at lo+lo + {}l.size$ + 1$.

A subtree does not know its own offset lolo. The same shape can hold keys 0..20..2 in one tree and 17..1917..19 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 i−1i-1 and ii is “gap ii”, and an nn-node tree has n+1n+1 gaps, numbered 0,…,n0, \dots, n. Growing the tree at gap ii adds a key there and shifts every rank at or after ii 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 α.

inductiveLabelledTreeno axiomsModels/Rotation/Abstract.lean:67
/-- A conventional node-labelled binary tree. Labels may be arbitrary keys. -/inductive LabelledTree (α : Type) where  | nil  | node (left : LabelledTree α) (key : α) (right : LabelledTree α)  deriving DecidableEq, Repr

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

defLabelledTree.eraseno axiomsModels/Rotation/Abstract.lean:73
/-- Forget the keys, keeping the entire shape. -/def LabelledTree.erase {α : Type} : LabelledTree α → Tree  | .nil => .nil  | .node l _ r => .node l.erase r.erase
defLabelledTree.inorderno axiomsModels/Rotation/Abstract.lean:78
/-- 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.inorder

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

defTree.labelFromno axiomsModels/Rotation/Abstract.lean:84
/-- 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 lo,lo+1,…,lo+lo, lo+1, \dots, lo + {}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].

Reading the Lean

Three things should hold, and Chapter 4 proves each of them:

  1. (t.labelFrom lo).erase = t. Labelling does not change the shape (Representation.erase_label).
  2. (t.labelFrom lo).inorder is the list lo, lo+1, …, so the labels are the ranks offset by lo (Representation.inorder_label).
  3. 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 nn-node shapes and BSTs on the keys 0,…,n−10, \dots, n-1.

The next two chapters work only with Tree. Accesses are stated in terms of ranks, as in “bring the node of rank xx to the root”, and labelled trees return in Chapter 4 to show that nothing was lost.