What is a splay tree, and how does it differ from an AVL tree?
A binary search tree that, after every access, moves the accessed node to the root with rotations, an operation called splaying. It stores no heights or balance information and gives no height guarantee; instead, recently and frequently used keys stay near the root.
An AVL tree enforces a shape rule and only rotates when the rule is broken. A splay tree has no shape rule at all. It rotates on every operation, including a plain search, which is unusual: reading the tree changes it.
The new operation is splay(x): rotate x upwards, step by step, until it is the root. Which node is splayed depends on the operation (the node found, the node inserted, or the parent of the node removed).
Two consequences follow:
- Locality pays off. A key you just used is at the root, so using it again costs $O(1)$, and keys used often never sink far. Workloads that keep returning to a small set of keys (caches, recently opened files, symbol tables while compiling one function) run faster than on any fixed balanced tree.
- A real example: the text buffer of GitHub's Atom editor kept the pending edits (patches) in a splay tree. Edits cluster around the cursor, so the part of the document being worked on stays near the root.
- No per-operation guarantee. The tree can become a long chain, and a single operation can then cost $O(n)$. The guarantee is only for sequences of operations: $O(\log n)$ each on average (amortised).
Go deeper:
Splay tree — splaying, the three step types, and the amortised analysis.
Splay tree visualisation (USF) — search a key and watch it rotate up to the root.