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 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.
For every binary search tree on keys and every key of , splaying is a root access: a sequence of legal rotations that ends with at the root. The number of rotations is exactly the count the algorithm reports, and it is less than .
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 to the root by rotations, at this cost” from Chapter 3.
The Lean statement
/-- 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 validModels.Rotation, Models.Online, Models.Pointer.Machine, Algorithms.Splay.Algorithm, Algorithms.Splay.Online, Bounds.WorkingSetBottom-up splaying, as defined in Section 2 of the splay tree paper (Sleator and Tarjan 1985), searches for the requested node and then repeats splaying steps until is the root. A step looks at , its parent and its grandparent :
- zig: if is the root, rotate over ;
- zig-zig: if and are both left children, or both right children, rotate over , then over ;
- zig-zag: otherwise, rotate over , then over .
Zig and zig-zag are exactly what move-to-root does; only zig-zig differs. That one change turns amortized rotations per request into .
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 , 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.
/-- 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 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.
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
/-- 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) cssplayAt l r cs splays the node = node l r up through its ancestor list cs. Each of the seven equations is one case of the description above. Below, ’s subtrees are and , its parent is and its grandparent is . Trees are written in parenthesized inorder, so is a node with left subtree and right subtree , and nodes appear in increasing key order.
[]: has no ancestors, so it is already the root. The result isnode l r.[.left b]: is the left child of the root , whose right subtree is . A zig rotates over : $$ which is.node l (.node r b).[.right a]: the mirror image, a zig with the right child of the root: $$.left b :: .left c :: cs: is the left child of , which is the left child of . Here is ’s right subtree and is ’s right subtree. A zig-zig rotates over , then over : $$ The new subtree of has left child and right child.node r (.node b c). That pair becomes the new focus, and splaying continues with the remaining ancestorscs..right a :: .right b :: cs: the mirror zig-zig. Here is ’s left subtree and is ’s left subtree: $$.right a :: .left b :: cs: is the right child of , which is the left child of . A zig-zag: $$.left b :: .right a :: cs: is the left child of , which is the right child of . The mirror zig-zag: $$
In each displayed transformation, the subtrees appear in the same left-to-right order on both sides, and so do , and . Equations 6 and 7 have the same right-hand side, splayAt (.node a l) (.node r b) cs, because both zig-zags leave between its two former ancestors. Only the variable names say which ancestor ends up on which side.
- A zig happens only when exactly one ancestor is left, that is, when 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 is carried as the focus, and the intermediate whole tree is
plug cs (.node l r). At the end the context is empty and 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,
.rightthen.right: first over , then over . In the zig-zag case they are.inLeft .leftthen.right: first over inside ’s left subtree, then over . These derivations are checked by the kernel. - The library’s tests separate zig-zig from rotating twice:
Splay.runon a three-node left path, requesting key , gives the right path, whilemoveToRootgives a different tree.
Theorem (splaying a focus). Let 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 , 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
/-- 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 : its depth. If the search ends at .nil (because x is out of range), run returns the tree unchanged with cost . 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 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 and every rank , run t x returns a tree and a count such that the tree is reached from by a root access to using exactly rotations, and .
/-- 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 validModels.Rotation, Models.Online, Models.Pointer.Machine, Algorithms.Splay.Algorithm, Algorithms.Splay.Online, Bounds.WorkingSetFor 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 and every rank , the pair returned by run t x is a root access to at the reported cost.
/-- 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).1Algorithms/Splay/Online/Abstract.lean and its imports/-- 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 hxAn 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 and every sequence of valid ranks, there is a pointer-machine execution that serves from , ends in exactly the tree that splaying produces, and costs at most , where is splaying’s total cost (requests plus rotations).
/-- 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 validModels.Rotation, Models.Online, Models.Pointer.Machine, Algorithms.Splay.Algorithm, Algorithms.Splay.Online, Bounds.WorkingSetThe 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 . A zig-zig needs four: move up to , rotate over , move back down to , rotate over . An access to depth therefore costs at most , and over a sequence the pointer cost is at most . 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.
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.
Set the figure to a left path with and request key , then keep the result and request key , then key . 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 amortized while splaying is .