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

Chapter 23Move-to-root

The simplest self-adjusting rule comes first. Move-to-root (Allen and Munro 1978) serves a request by finding xx and then rotating it over its parent, again and again, until it is the root. Recently requested keys stay near the top, which is the intuition behind every self-adjusting tree. Under independent random requests, Allen and Munro showed that its expected cost is within a constant factor of the optimal static tree. In the worst case it is poor: a sequential scan costs Θ(n)\Theta(n) rotations per request, forever. Splaying (Section 24.1) repairs exactly this defect by rotating in pairs.

What the library proves about move-to-root is that it is correct: it really performs an access in the rotation model, and it reports its rotation count truthfully. It proves no amortized bound, in either direction. The poor behaviour on scans is shown at the end of the chapter as a measurement.

Main result · Allen and Munro 1978
Move-to-root performs a legal access with fewer than nn rotations

Let tt be any binary search tree on nn keys and xx any of its keys. Move-to-root returns a tree uu and a count kk such that kk rotations turn tt into uu, the key xx is the root of uu, and k<nk < n.

In Lean, the algorithm is the function moveToRoot, which returns the pair (u,k)(u, k). The conclusion is Access from Chapter 3: a sequence of exactly kk rotations from tt to uu, with xx at the root of uu.

The Lean statement
theoremMoveToRoot.Results.correctpropext · Classical.choice · Quot.soundAlgorithms/MoveToRoot/Abstract.lean:15
/-- Move-to-root exposes the requested rank with a legal rotation trace, usingfewer than `size` rotations. -/theorem correct (t : Tree) (x : Nat) (valid : x < t.size) :    Access t (moveToRoot t x).1 x (moveToRoot t x).2 ∧ (moveToRoot t x).2 < t.size := …  moveToRoot_correct t x valid
6 definitions in 4 chapters · reading list

In the library, move-to-root plays a second role. It is the constructive witness for the existence results of the rotation model (Chapter 3): every existing key can be brought to the root, with fewer rotations than there are nodes.

23.1 The algorithm

defmoveToRootno axiomsAlgorithms/MoveToRoot/Algorithm/Abstract.lean:12
/-- Recursively expose x in its child subtree, then rotate it one level up.Out-of-range inputs have arbitrary behavior; correctness is required only in range. -/def moveToRoot : Tree → Nat → Tree × Nat  | .nil, _ => (.nil, 0)  | .node l r, x =>      if x < l.size then        let (u, k) := moveToRoot l x        match u with        | .nil => (.node l r, 0)        | .node a b => (.node a (.node b r), k + 1)      else if x = l.size then (.node l r, 0)      else        let (u, k) := moveToRoot r (x - l.size - 1)        match u with        | .nil => (.node l r, 0)        | .node a b => (.node (.node l a) b, k + 1)

moveToRoot t x returns the new tree and the number of rotations performed. It follows the three-way search on ranks of Chapter 1:

  • If x < l.size, the key is in the left subtree. The recursive call returns a tree u with x at its root, u = node a b. One right rotation at the root of node u r then lifts x above its parent: node (node a b) r becomes node a (node b r). The cost is the recursive cost plus one.
  • If x = l.size, the key is already the root, and nothing happens.
  • Otherwise the key is in the right subtree, at rank x - l.size - 1 there, and the mirror-image left rotation lifts it.

The rotations are performed on the way back from the recursion, so the deepest one comes first. Each is a rotation at the root of the current subtree, which in the whole tree is a Rotate.right or .left wrapped in inLeft/inRight constructors. The number of rotations is the depth of xx.

Reading the Lean
  • The two branches | .nil => (.node l r, 0) cannot occur for a valid rank: when x < l.size, the left subtree is nonempty and its recursive result has a root. They make the function total, as does the arbitrary result for out-of-range ranks, which the docstring states explicitly.
  • x - l.size - 1 is truncated subtraction on Nat. It is only evaluated when x > l.size, so it never truncates.
  • The function returns its own cost. Nothing in the definition prevents a wrong count; the theorem below ties it to an actual rotation sequence.

23.2 Correctness

Theorem (correctness of move-to-root). For every tree t and every rank x < t.size, the pair (moveToRoot t x) is a legal root access: there is a sequence of exactly (moveToRoot t x).2 rotations from t to the returned tree, and the returned tree has x at its root. Moreover the count is below t.size.

theoremMoveToRoot.Results.correctpropext · Classical.choice · Quot.soundAlgorithms/MoveToRoot/Abstract.lean:15
/-- Move-to-root exposes the requested rank with a legal rotation trace, usingfewer than `size` rotations. -/theorem correct (t : Tree) (x : Nat) (valid : x < t.size) :    Access t (moveToRoot t x).1 x (moveToRoot t x).2 ∧ (moveToRoot t x).2 < t.size :=  moveToRoot_correct t x valid

The “statement reads only” line shows that this theorem depends on nothing but the rotation model and the definition above.

This is the witness behind access_exists_iff. The count is in fact exactly the depth of xx, which is at most t.size - 1; the library states only the weaker bound, which is what the existence result needs.

23.3 As an online algorithm

Packaged as an Algorithm, move-to-root ignores the request history:

defmoveToRootAlgorithmpropext · Classical.choice · Quot.soundAlgorithms/MoveToRoot/Abstract.lean:23
/-- A baseline algorithm, not splaying: single rotations move the request upward. -/def moveToRootAlgorithm : Algorithm where  step _ t x := moveToRoot t x  correct _ t x hx := (moveToRoot_correct t x hx).1

The certificate correct is the first conjunct of the theorem above. All the definitions of Chapter 5 and Part II therefore apply to it: moveToRootAlgorithm.cost, its total cost, and the properties HasWorkingSetBound and the others of Chapter 14. The library proves none of those properties for move-to-root, and they fail: on the repeated scans below, the cost per request grows linearly in nn, while every benchmark of Part II charges a scan request O(log⁡n)O(\log n).

23.4 Why it is not enough

Start from a left path on nn keys, the tree whose root is n−1n-1 and whose every node has only a left child, and request 0,1,…,n−10, 1, \dots, n-1. Key 00 is at depth n−1n-1; moving it to the root costs n−1n-1 rotations and leaves keys 1,…,n−11, \dots, n-1 in a path hanging from its right child. Each later request is again at the bottom of that path. The scan ends in a left path again, so the next scan costs the same. The figure measures n(n+1)/2−1n(n+1)/2 - 1 rotations per scan, Θ(n)\Theta(n) per request.

The reason is that move-to-root brings xx to the top but pushes every other node of the access path down by one level. The path does not get shorter, it just changes which node is at its top. Splaying differs from move-to-root in one case only. When xx and its parent are both left children, or both right children, it rotates the parent over the grandparent first and then xx over its parent (the zig-zig step). This roughly halves the depth of every node on the access path. The same scan then costs O(n)O(n) in total, the sequential access theorem.

The two algorithms on other sequences

With sequential scans on a left path of 6363 keys, move-to-root pays 20152015 rotations per scan and splaying about 250250. Switch to uniform random requests: the two curves are close, in line with Allen and Munro’s average-case analysis. The difference between the algorithms is in the worst case, and only splaying has the amortized guarantees of Section 24.2.

Measured, not proved

The library proves no lower bound for move-to-root. The quadratic scan above is a measurement of the JavaScript port of moveToRoot, which the test suite checks against Lean on all shapes with at most five nodes and on random larger trees. It is not a theorem.