Most balanced trees treat every key equally. A splay tree plays favourites — cleverly. Every time you search, insert, or delete a node, it splays that node to the root through a sequence of rotations. The payoff: keys you use often, or used recently, drift toward the top and become cheap to reach again — a tree that adapts its shape to your access pattern with no stored balance factors, colors, or extra fields at all. Operations are O(log n)amortized. Access a few keys and watch each one get yanked up to the root.
O(log n) amortized · every access splays the node to the root · no balance metadata
splay
Rotate a node up to the root through zig / zig-zig / zig-zag steps.
self-adjusting
The tree restructures on every access — hot keys migrate toward the top.
amortized
Any single op may be slow, but any sequence averages O(log n) per op.
no metadata
Unlike AVL/red-black, nodes store no balance factor or color — just splaying.
splay.js — the root is whatever you touched last
Ready
A binary search tree. Every time you access a key, the tree splays it — rotating it all the way to the root. Recently used keys stay near the top. Access a key and watch it rise.
–
root now
–
accessed
0
height
How it works
Splaying moves a node to the root using three cases, applied repeatedly until it arrives. A zig is a single rotation used when the node’s parent is the root. A zig-zig handles the case where node and parent are both left children (or both right): you rotate the grandparent first, then the parent — this is the key case that keeps long paths from re-forming. A zig-zag handles the node being a left child of a right child (or vice versa): rotate the parent, then the grandparent. Each access does O(depth) work but also roughly halves the depth of everything along the path, which is why a whole sequence of operations averages to O(log n) each — the amortized guarantee.
1
Find the key as usual
Descend the BST by comparisons to locate the key (or where it would go, for insertion).
2
Splay it to the root
Rotate the node upward using zig, zig-zig, and zig-zag steps until it becomes the root. BST order is preserved throughout.
3
Reap the locality
The just-accessed key is now the root, and everything along its old path got shallower. Accessing it again — or nearby keys — is now cheap.
✓
Amortized O(log n)
A single splay can cost O(n) on a bad tree, but the restructuring pays for itself: any sequence of m operations runs in O(m log n) total. No balance metadata is ever stored.
Operations
O(log n) amort.
Worst single op
O(n)
Metadata
none
Great for
skewed access
The code
# after finding a node, splay it to the root (bottom-up sketch)def splay(node):
while node.parent:
p, g = node.parent, node.parent.parent
if g isNone:
rotate(node) # zig: p is rootelif (node is p.left) == (p is g.left):
rotate(p); rotate(node) # zig-zig: same sideelse:
rotate(node); rotate(node) # zig-zag: opposite sides# every access ends with the touched node at the root
Quick check
1. What does a splay tree do on every access?
Every search, insert, or delete ends by splaying the touched node to the root through rotations. This makes recently and frequently used keys cheap to reach again.
2. What does “O(log n) amortized” mean for a splay tree?
Amortized means the guarantee is over a sequence: one splay can be O(n) on a bad shape, but the restructuring it does makes later operations cheaper, so any sequence averages O(log n) per operation.
3. What extra per-node metadata does a splay tree store versus AVL or red-black trees?
Splay trees keep no balancing metadata. AVL trees store heights/balance factors and red-black trees store colors; a splay tree just splays on access, which is part of its appeal.
FAQ
What is a splay tree?
A self-adjusting BST that moves every accessed node to the root via rotations ("splaying"), keeping recently/frequently used keys near the top for fast repeat access. It stores no balancing metadata and achieves O(log n) amortized search, insert, and delete.
What are zig, zig-zig, and zig-zag?
The three splay cases. Zig: a single rotation when the parent is the root. Zig-zig: node and parent on the same side (both left or both right) — rotate grandparent then parent. Zig-zag: opposite sides — rotate parent then grandparent. Repeating them lifts the node to the root.
When are splay trees a good choice?
When access is skewed or has temporal locality — splay trees exploit it automatically, often beating balanced trees on cache-like workloads, and they’re simple with easy split/merge. Downsides: no worst-case per-op bound, and every access mutates the tree (bad for concurrent reads).
How do splay trees compare to AVL and red-black trees?
AVL/red-black guarantee worst-case O(log n) per op via stored balance data. Splay trees give O(log n) amortized only (a single op can be O(n)), store no balance data, adapt to access patterns, and are simpler. Balanced trees for worst-case bounds or concurrent reads; splay trees for locality and simplicity.
The picture: one access, a whole path folded
The page’s keys inserted in the order 5, 3, 8, 1, 4, 7, 9 leave a lopsided tree: 9 on top, then 8, 7, 5, 4, 3, 1 hanging down its left side. search(3) costs 6 node visits and rotates 3 to the root. No key on the old path is deeper than level 4 afterwards, and the height drops from 7 to 4.
Worked example, step by step
Run the page’s own sequence on an empty splay tree: insert 5, 3, 8, 1, 4, 7, 9, then search(3), search(9) and search(3) again. The tree is written as key(left,right) with . for an empty side. “Nodes visited” counts the descent before the splay, including the node that ends up at the root.
#
Operation
Nodes visited
New root
Tree after
Height
1
insert(5)
0
5
5
1
2
insert(3)
1
3
3(.,5)
2
3
insert(8)
2
8
8(5(3,.),.)
3
4
insert(1)
3
1
1(.,3(.,5(.,8)))
4
5
insert(4)
3
4
4(3(1,.),5(.,8))
3
6
insert(7)
3
7
7(5(4(3(1,.),.),.),8)
5
7
insert(9)
2
9
9(8(7(5(4(3(1,.),.),.),.),.),.)
7
8
search(3)
6
3
3(1,8(5(4,7),9))
4
9
search(9)
3
9
9(8(3(1,5(4,7)),.),.)
5
10
search(3)
3
3
3(1,8(5(4,7),9))
4
Three things stand out. First, the inserts build a bad tree on this input: by step 7 the tree is a chain of height 7, because 9 is bigger than everything and each splay leaves the previous maximum below it. No balance rule stopped that. Second, step 8 is the repair: the one search of 3 visited 6 nodes, then turned the chain into a tree of height 4. Third, step 10 is the payoff: asking for 3 again visits 1 node, because it is already the root. Step 9 shows the other side of the bargain: reaching for 9 pulled 3 down to depth 3 and the height went back up to 5. Recently used keys are cheap; the rest pay a little to make room.
Complexity and trade-offs
Case
Time
Space
Why
Splay tree
O(log n) amortized; one operation can be O(n)
O(n)
No balance fields. Any run of m operations costs O(m log n) in total; skewed access is cheaper.
Plain BST, no rebalancing
O(n) per operation worst case
O(n)
Sorted input makes a chain, and nothing ever repairs it.
AVL or red-black tree
O(log n) worst case per operation
O(n) plus balance data
Every single operation is bounded; the price is height or colour bookkeeping on each node.
Treap
O(log n) expected
O(n) plus a priority
Balance comes from random priorities rather than from access history.
Move-to-root (single rotations)
O(n) amortized in the worst case
O(n)
Looks like splaying but loses the guarantee; see the mistakes below.
Measured on a chain of 100 keys (insert 1 to 100 in order) with accesses 1, 2, …, 100: total nodes visited were 591 for splaying, 5,050 for a plain BST that never changes shape, and 5,149 for move-to-root. The first access costs the full 100 visits in all three; only splaying makes the later ones cheap. What you give up is predictability: a single splay can be slow, every lookup is a write, and a read-only workload still mutates the tree.
Common mistakes
Rotating the node twice for zig-zig
When node and parent are on the same side, the grandparent must be rotated first, then the parent. Using two single rotations of the node alone (move-to-root) keeps long paths long. On the 100-key chain accessed in order, that costs 5,149 node visits against 591 for the real splay.
Not splaying after a miss
When the key is absent, the last node visited still sits at the bottom of a deep path, and splaying it is what pays for the search. On the 100-key chain, 50 searches for the missing key 0 cost 149 visits in total when each miss splays (100 for the first, then 1 each) and 5,000 when the tree is left alone.
Holding on to the old root
Every search can change tree.root. In the example the root is 9 before search(3) and 3 after; the old root 9 is now a leaf with no children, so code that kept it and searches from there will miss keys that are still in the tree. Always read the root back from the tree object.
Expecting lookups to be read-only
A search rewrites pointers, so two threads searching the same tree at the same time are both writers. A shared splay tree needs a lock even for lookups, and iterating it while searching can also see a changing shape.
Recursing down a long path
The recursive splay uses one stack frame per level. After inserting 1 to 2000 in order, search(1) has to descend 2000 levels and Python raised RecursionError. The tree is legal; the implementation is not. Use an iterative or top-down splay for large inputs.
Where this shows up
Workloads with locality
When a small set of keys receives most of the lookups, such as recently used entries in a symbol table or a cache index, those keys stay near the root with no extra bookkeeping. A balanced tree treats every key the same and cannot take advantage of that.
Split and join
Because splaying a key to the root cuts the tree into “smaller” and “larger” halves, splitting at a key and joining two trees are both a splay plus a pointer change. That is why splay trees are a common backbone for ordered-sequence structures that need those operations.
Inside link-cut trees
Link-cut trees, used for dynamic forest problems, are commonly implemented by keeping each preferred path in a splay tree. The amortized bound is what makes the combined structure fast.
Interviews and teaching
Splay trees show up as the answer to “design a BST with no balance field” and as the standard example of amortized analysis, where a costly operation is paid for by the restructuring it does.
SOLVE IT YOURSELF
Solve it: splay the key you just touched
Most balanced trees fight to stay symmetric. A splay tree does the opposite: every time you touch a key it rotates that key to the root. Frequently-used keys drift to the top, so real access patterns beat the balanced worst case. Python or TypeScript.
YOUR TASK
Implement SplayTree with insert(key), search(key), delete(key) and inorder(). After any successful operation the touched key must be sitting at the root.
HINTS — 8 IDEAS
Splaying moves a node to the root by repeated rotations — but not one at a time. The pair of rotations you pick is what makes it work.
zig-zig (node and parent lean the same way): rotate the grandparent first, then the parent. Rotating the node twice instead would leave the path just as deep.
zig-zag (they lean opposite ways): rotate the parent, then the grandparent.
zig (the parent is the root): one rotation and you are done.
That zig-zig ordering is the entire amortised argument — it roughly halves the depth of every node on the access path, so one long walk pays for the next several.
Insert by splaying first: the tree then splits cleanly at the root into everything-smaller and everything-larger, and the new node adopts both.
Delete by splaying the doomed key to the root, then splaying the largest key of its left subtree to that subtree's root — that node has no right child, so the right subtree hangs straight off it.
A single search can still leave the tree tall. That is allowed: splay trees promise an amortised O(log n), not a per-operation bound.