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

Chapter 24 · Splay trees · Section 24.1Splaying

Splay trees, introduced by Sleator and Tarjan in 1985, are the best-known self-adjusting BST. They store no balance information. After every access they move the accessed node to the root by a fixed rotation pattern, and the analysis shows that this alone yields O(log⁡n)O(\log n) amortized cost, and much more on structured sequences. This section defines the algorithm, proves it is a legal BST algorithm, and shows it can be run on the pointer machine. Its cost guarantees come in the next two sections. Section 24.2 proves the balance theorem, static optimality, the static finger bound and the working-set bound. Section 24.3 treats updates, long splays, snapshots and sequential access.

Splaying is a legal BST algorithm

For every binary search tree tt on nn keys and every key xx of tt, splaying xx is a root access: a sequence of legal rotations that ends with xx at the root. The number of rotations is exactly the count the algorithm reports, and it is less than nn.

In Lean, the algorithm is Splay.run, which returns the new tree and its rotation count. correct concludes an Access, the certified notion of “bring xx to the root by rotations, at this cost” from Chapter 3.

The Lean statement
theoremSplay.Results.correctpropext · Quot.soundAlgorithms/Splay/Abstract.lean:23
/-- Splay exposes exactly the requested rank using a legal rotation trace.Its rotation count is the depth of that rank, hence less than the number of nodes. -/theorem correct (t : Tree) (x : Nat) (valid : x < t.size) :    Access t (run t x).1 x (run t x).2 ∧ (run t x).2 < t.size := …  run_correct t x valid
10 definitions in 5 chapters · reading list

Bottom-up splaying, as defined in Section 2 of the splay tree paper (Sleator and Tarjan 1985), searches for the requested node xx and then repeats splaying steps until xx is the root. A step looks at xx, its parent pp and its grandparent gg:

  • zig: if pp is the root, rotate xx over pp;
  • zig-zig: if xx and pp are both left children, or both right children, rotate pp over gg, then xx over pp;
  • zig-zag: otherwise, rotate xx over pp, then xx over gg.

Zig and zig-zag are exactly what move-to-root does; only zig-zig differs. That one change turns Θ(n)\Theta(n) amortized rotations per request into O(log⁡n)O(\log n).

The library implements this without parent pointers, in two purely functional phases. locate performs the search and returns the search path as a zipper: the subtree rooted at xx, together with the list of its ancestors. splayAt then consumes that list two ancestors at a time. This section goes through both, checks each equation against the three cases above, and then states what has been proved about the result.

24.1.1 Searching with a zipper

The search path is recorded with the frames of the pointer machine (Chapter 7). A frame describes one ancestor from the point of view of its child on the path: Frame.left r means “the path went into the left child of this ancestor, whose right subtree is r”, and Frame.right l is the mirror image. A list of frames, nearest ancestor first, is enough to rebuild the whole tree around a focused subtree; this is plug. The rank of the focused subtree’s smallest key is offset of the context: every .right l frame contributes the l.size + 1 keys of its left subtree and root.

defSplay.locateno axiomsAlgorithms/Splay/Algorithm/Abstract.lean:25
/-- Ordinary rank search; the nearest ancestor is first in the context. -/def locate : Tree → Nat → Config  | .nil, _ => ⟨.nil, []⟩  | .node l r, x =>      if x < l.size then        let c := locate l x        ⟨c.focus, c.context ++ [.left r]⟩      else if x = l.size then ⟨.node l r, []⟩      else        let c := locate r (x - l.size - 1)        ⟨c.focus, c.context ++ [.right l]⟩

This is ordinary search by rank. At node l r, the root has rank l.size within the subtree. A smaller x continues in l with the same relative rank. A larger x continues in r with relative rank x - l.size - 1. That subtraction is only evaluated when x > l.size, so it never truncates. The recursive result’s context is extended at the end by the frame for the current node (c.context ++ [.left r]). The current node is the farthest ancestor of everything found below it, so the finished context lists the nearest ancestor first and the root last.

The returned Config has the subtree rooted at xx as its focus, and the context as its ancestor list. If x is out of range, the search falls off the tree and the focus is .nil.

Reading the Lean

The library proves that locate does what this description says, for every rank in range. Plugging the context back around the focus gives the original tree. The focus is the node of rank x, which is key? = offset context + l.size. The context is shorter than the tree size. This is the lemma Splay.locate_correct.

The number of frames is also exactly the ordinary search depth: (locate t x).context.length = t.depth x (Splay.locate_depth, with Tree.depth from Chapter 1). Both lemmas are proof-level facts, outside the reading interface, so their Lean is not quoted here.

24.1.2 The splaying steps

defSplay.splayAtno axiomsAlgorithms/Splay/Algorithm/Abstract.lean:15
/-- Splay the focused node through its ancestors, two at a time. -/def splayAt (l r : Tree) : List Frame → Tree  | [] => .node l r  | [.left b] => .node l (.node r b)  | [.right a] => .node (.node a l) r  | .left b :: .left c :: cs => splayAt l (.node r (.node b c)) cs  | .right a :: .right b :: cs => splayAt (.node (.node b a) l) r cs  | .right a :: .left b :: cs => splayAt (.node a l) (.node r b) cs  | .left b :: .right a :: cs => splayAt (.node a l) (.node r b) cs

splayAt l r cs splays the node xx = node l r up through its ancestor list cs. Each of the seven equations is one case of the description above. Below, xx’s subtrees are ll and rr, its parent is pp and its grandparent is gg. Trees are written in parenthesized inorder, so (A p B)(A\,p\,B) is a node pp with left subtree AA and right subtree BB, and nodes appear in increasing key order.

  1. []: xx has no ancestors, so it is already the root. The result is node l r.
  2. [.left b]: xx is the left child of the root pp, whose right subtree is bb. A zig rotates xx over pp: $((l x r) p b)  →  (l x (r p b)),((l\,x\,r)\,p\,b) \;\to\; (l\,x\,(r\,p\,b)),$ which is .node l (.node r b).
  3. [.right a]: the mirror image, a zig with xx the right child of the root: $(a p (l x r))  →  ((a p l) x r).(a\,p\,(l\,x\,r)) \;\to\; ((a\,p\,l)\,x\,r).$
  4. .left b :: .left c :: cs: xx is the left child of pp, which is the left child of gg. Here bb is pp’s right subtree and cc is gg’s right subtree. A zig-zig rotates pp over gg, then xx over pp: $(((l x r) p b) g c)  →  (l x (r p (b g c))).(((l\,x\,r)\,p\,b)\,g\,c) \;\to\; (l\,x\,(r\,p\,(b\,g\,c))).$ The new subtree of xx has left child ll and right child .node r (.node b c). That pair becomes the new focus, and splaying continues with the remaining ancestors cs.
  5. .right a :: .right b :: cs: the mirror zig-zig. Here aa is pp’s left subtree and bb is gg’s left subtree: $(b g (a p (l x r)))  →  (((b g a) p l) x r).(b\,g\,(a\,p\,(l\,x\,r))) \;\to\; (((b\,g\,a)\,p\,l)\,x\,r).$
  6. .right a :: .left b :: cs: xx is the right child of pp, which is the left child of gg. A zig-zag: $((a p (l x r)) g b)  →  ((a p l) x (r g b)).((a\,p\,(l\,x\,r))\,g\,b) \;\to\; ((a\,p\,l)\,x\,(r\,g\,b)).$
  7. .left b :: .right a :: cs: xx is the left child of pp, which is the right child of gg. The mirror zig-zag: $(a g ((l x r) p b))  →  ((a g l) x (r p b)).(a\,g\,((l\,x\,r)\,p\,b)) \;\to\; ((a\,g\,l)\,x\,(r\,p\,b)).$

In each displayed transformation, the subtrees appear in the same left-to-right order on both sides, and so do pp, gg and xx. Equations 6 and 7 have the same right-hand side, splayAt (.node a l) (.node r b) cs, because both zig-zags leave xx between its two former ancestors. Only the variable names say which ancestor ends up on which side.

Reading the Lean
  • A zig happens only when exactly one ancestor is left, that is, when pp is the root of the whole tree, as in the paper. With two or more ancestors, the step is always a double one.
  • Splaying never plugs anything back into the tree. The new subtree of xx is carried as the focus, and the intermediate whole tree is plug cs (.node l r). At the end the context is empty and xx is the root.
  • The equations alone do not show that the double steps are the paper’s rotation sequences, as opposed to some other restructuring with the same result. The correctness lemma below fixes this, because its proof gives the rotations explicitly. In the zig-zig case they are two root rotations at the grandparent’s position, .right then .right: first pp over gg, then xx over pp. In the zig-zag case they are .inLeft .left then .right: first xx over pp inside gg’s left subtree, then xx over gg. These derivations are checked by the kernel.
  • The library’s tests separate zig-zig from rotating xx twice: Splay.run on a three-node left path, requesting key 00, gives the right path, while moveToRoot gives a different tree.

Theorem (splaying a focus). Let xx be the root of the subtree node l r, sitting below the ancestors cs in the tree plug cs (node l r). Then splayAt l r cs is reached from that tree by a root access to xx, whose rank is offset cs + l.size, using exactly cs.length rotations, one per ancestor. In the library this is Splay.splayAt_correct, the lemma from which Results.correct below is derived.

This is the invariant behind everything that follows; “root access” is in the sense of Chapter 3. A zig uses one rotation for one frame, and a double step uses two rotations for two frames, so the count is exact.

24.1.3 The splay function

defSplay.runno axiomsAlgorithms/Splay/Algorithm/Abstract.lean:37
/-- The returned count is the exact number of rotations, one per search ancestor.Out-of-range inputs are outside the algorithm's correctness contract. -/def run (t : Tree) (x : Nat) : Tree × Nat :=  let c := locate t x  match c.focus with  | .nil => (t, 0)  | .node l r => (splayAt l r c.context, c.context.length)

run t x searches, then splays, and reports the splayed tree with its rotation count. That count is c.context.length, the number of ancestors of xx: its depth. If the search ends at .nil (because x is out of range), run returns the tree unchanged with cost 00. No theorem relies on this case; every statement about run assumes x < t.size.

The figure runs a transcription of locate, splayAt and run. Each Step applies one equation, and the corresponding line of splayAt above is highlighted. The panel shows the remaining context in the same notation as the Lean source. A left path on nn keys is the classical bad start: one access to a deep key roughly halves the depth of every node on the path. Use Keep result to request another key from the splayed tree.

24.1.4 Correctness

Theorem (correctness of splaying). For every tree tt and every rank x<∣t∣x < |t|, run t x returns a tree and a count kk such that the tree is reached from tt by a root access to xx using exactly kk rotations, and k<∣t∣k < |t|.

theoremSplay.Results.correctpropext · Quot.soundAlgorithms/Splay/Abstract.lean:23
/-- Splay exposes exactly the requested rank using a legal rotation trace.Its rotation count is the depth of that rank, hence less than the number of nodes. -/theorem correct (t : Tree) (x : Nat) (valid : x < t.size) :    Access t (run t x).1 x (run t x).2 ∧ (run t x).2 < t.size :=  run_correct t x valid

For every rank in range, the pair returned by run is certified by an Access. The rotations are legal (each is a Rotate step in the sense of Chapter 2), the final root has rank x, the cost is exactly the reported count, and that count is less than t.size. The proof combines locate_correct with splayAt_correct: plug of the context around the focus is t, and offset cs + l.size = x.

24.1.5 Splay as an online algorithm

To compare splaying with other algorithms over whole request sequences, it is packaged as an online algorithm. The certificate the package requires is the correctness theorem again, in the form the package asks for.

Theorem (splay step). For every tree tt and every rank x<∣t∣x < |t|, the pair returned by run t x is a root access to xx at the reported cost.

theoremSplay.step_correctpropext · Quot.soundAlgorithms/Splay/Online/Abstract.lean:9
/-- The certificate used by the bundled online algorithm. -/theorem step_correct (t : Tree) (x : Nat) (valid : x < t.size) :    Access t (run t x).1 x (run t x).2 :=  (run_correct t x valid).1
Statement reads only Algorithms/Splay/Online/Abstract.lean and its imports
defSplay.algorithmpropext · Quot.soundAlgorithms/Splay/Online/Abstract.lean:14
/-- The splay algorithm is online and uses no persistent state beyond its tree. -/def algorithm : Algorithm where  step _ t x := run t x  correct _ t x hx := step_correct t x hx

An Algorithm (Chapter 5) is a step function from the past requests, the current tree and the current request, together with a certificate that each valid step is an Access. Splay’s step is run t x. The first argument, the request history, is ignored (the _). The analysis weights of Section 24.2 appear nowhere. Splay is online in the strictest sense: it sees only the current shape and the current request.

From here on, algorithm.cost t xs is the total number of splay rotations over the sequence xs, and algorithm.totalCost t xs adds one unit per request (Chapter 5).

24.1.6 A pointer implementation

The rotation model charges nothing for walking down the tree. This splay implementation is nevertheless realizable on the single-cursor pointer machine of Chapter 7, with the same final tree and constant overhead.

Theorem (splaying on the pointer machine). For every tree tt and every sequence XX of valid ranks, there is a pointer-machine execution that serves XX from tt, ends in exactly the tree that splaying produces, and costs at most 3(m+R)3(m + R), where m+Rm + R is splaying’s total cost (requests plus rotations).

theoremSplay.Results.pointer_executionpropext · Quot.soundAlgorithms/Splay/Abstract.lean:29
/-- This concrete splay algorithm has a constant-factor pointer implementationwith exactly the same final shape. -/theorem pointer_execution (t : Tree) (xs : List Nat) (valid : ∀ x ∈ xs, x < t.size) :    ∃ k, k ≤ 3 * algorithm.totalCost t xs ∧      Pointer.Execution t xs (algorithm.runFrom [] t xs).1 k :=  Bridge.pointer_execution t xs valid

The proof follows each access on the pointer machine. The search costs one downward move per frame. A zig is one rotation instruction. A zig-zag is two rotation instructions with the cursor staying on xx. A zig-zig needs four: move up to pp, rotate pp over gg, move back down to xx, rotate xx over pp. An access to depth dd therefore costs at most 1+d+2d1 + d + 2d, and over a sequence the pointer cost is at most m+3R≤3(m+R)m + 3R \le 3(m+R). The final tree is exactly (algorithm.runFrom [] t xs).1, not merely some tree reachable from it, so the comparison is with the same execution.

What is not charged

Search by rank compares x with l.size. The Lean function recomputes subtree sizes, but the cost models count abstract BST operations, not the evaluation time of the Lean code. In a conventional implementation with stored keys, the same branch is decided by one key comparison per node, which the pointer machine already pays for with the move.

Splay versus move-to-root

Set the figure to a left path with n=15n = 15 and request key 00, then keep the result and request key 11, then key 22. Each access costs its depth, and the depths fall quickly. Move-to-root on the same sequence leaves a path of nearly the same depth after each access (Chapter 23). This is the standard example where single rotations are Θ(n)\Theta(n) amortized while splaying is O(log⁡n)O(\log n).