Splay Trees
A splay tree is a self-adjusting binary search tree: every access rotates the touched node to the root, so frequently used keys stay near the top and every operation costs O(log n) amortized.
A Self-Adjusting BST
A splay tree is a self-adjusting binary search tree invented by Daniel Sleator and Robert Tarjan in 1985. It keeps the ordinary BST property (smaller keys on the left, larger on the right) but stores no height, colour or balance field. Instead, every time a node is accessed, a sequence of rotations called splaying moves that node to the root.
The tree is not kept balanced. It can become a long path, and one search on it can cost O(n). But each expensive access also restructures the path it walked, roughly halving the depth of the nodes on it, so any sequence of m operations on n keys costs O(m log n) in total. Each operation is O(log n) amortized.
- Splaying: rotating an accessed node x up to the root
- Self-adjusting: the shape follows the access pattern, not a balance rule
- Recently used keys sit near the root, so repeated access is fast
Splaying: Zig, Zig-Zig and Zig-Zag Rotations
- Zig – p is the root: rotate x above p. Used at most once, as the last step.
- Zig-zig – x and p are both left children (or both right children): rotate p above g, then x above p.
- Zig-zag – x is a right child and p a left child, or the reverse: rotate x above p, then x above g.
- Repeat – continue from x's new position until x has no parent.
Splaying moves node x to the root in steps. Each step looks at x, its parent p and its grandparent g, and applies one of three cases until x is the root. Each case is built from ordinary BST rotations, which never change the in-order sequence of keys.
The case that matters is zig-zig. Rotating x above p twice (the naive move-to-root) can leave a long path long. Rotating g–p first, then p–x folds the path, and it is this order that gives the structure its O(log n) amortized bound.
- Zig-zig and zig-zag move x up two levels; zig moves it one
- A node at depth d is splayed in about d/2 steps
- Mirror images count as the same case (zig-zig on the right, zag-zag in some books)
Search, Insert and Delete
Every operation is an ordinary BST operation followed by one splay. That single rule is the whole algorithm.
Search(k): walk down as in a BST. If k is found, splay it. If not, splay the last node visited, so an unsuccessful search is also paid for. Insert(k): insert k as a new leaf, then splay it to the root. Delete(k): splay k to the root, remove it, leaving left subtree L and right subtree R; splay the largest key in L to L's root (it then has no right child) and attach R as its right child.
- Split(k): splay k, then cut off its right subtree; everything left is ≤ k
- Join(L, R), every key in L below every key in R: splay max(L) and make R its right child
- Split and join are cheap because the splayed node is at the root
- A top-down variant splays while descending, in one pass without parent pointers
Terms, operations, and practical uses
Core vocabulary
- SplayingRotating an accessed node to the root in zig, zig-zig and zig-zag steps.
- ZigOne rotation, used when the parent is the root.
- Zig-zigSame-side case: rotate the parent above the grandparent first, then x.
- Zig-zagOpposite-side case: rotate x above its parent, then above its grandparent.
Formulas
- Rankr(x) = log₂ size(x), the size of x's subtree.
- PotentialΦ = Σ r(x) over all nodes.
- Access lemmaAmortized cost of splaying x ≤ 3(r(root) − r(x)) + 1.
- Sequence boundm operations on n keys: O(m log n + n log n).
Related lessons
- Binary Search TreesThe search, insert and delete that splaying finishes.
- AVL TreesWorst-case balance with the same rotations.
- Red-Black TreesThe balanced BST behind most library maps.
- Amortized AnalysisThe potential method behind the O(log n) bound.
Code in Python, C++ and Java
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
self.parent = None
class SplayTree:
def __init__(self):
self.root = None
self.steps = []
def rotate(self, x):
# Lift x above its parent p, keeping the in-order sequence unchanged.
p = x.parent
g = p.parent
if p.left is x:
p.left = x.right
if x.right:
x.right.parent = p
x.right = p
else:
p.right = x.left
if x.left:
x.left.parent = p
x.left = p
p.parent = x
x.parent = g
if g is None:
self.root = x
elif g.left is p:
g.left = x
else:
g.right = x
def splay(self, x):
while x.parent:
p = x.parent
g = p.parent
if g is None:
self.steps.append(f"zig({x.key})")
self.rotate(x)
elif (g.left is p) == (p.left is x):
self.steps.append(f"zig-zig({x.key})")
self.rotate(p)
self.rotate(x)
else:
self.steps.append(f"zig-zag({x.key})")
self.rotate(x)
self.rotate(x)
def insert(self, key):
parent, node = None, self.root
while node:
parent = node
node = node.left if key < node.key else node.right
x = Node(key)
x.parent = parent
if parent is None:
self.root = x
elif key < parent.key:
parent.left = x
else:
parent.right = x
self.splay(x)
def search(self, key):
# Returns (found, depth of the last node visited before splaying).
node, last, depth = self.root, None, -1
while node:
last = node
depth += 1
if key == node.key:
break
node = node.left if key < node.key else node.right
if last:
self.splay(last)
return node is not None, depth
def preorder(self):
out = []
def walk(n):
if n:
out.append(str(n.key))
walk(n.left)
walk(n.right)
walk(self.root)
return " ".join(out)
def height(n):
return -1 if n is None else 1 + max(height(n.left), height(n.right))
def report(tree, label):
steps = ", ".join(tree.steps) if tree.steps else "none"
print(f"{label:<12} rotations: {steps}")
print(f"{'':<12} preorder: {tree.preorder()} (height {height(tree.root)})")
tree.steps = []
tree = SplayTree()
for k in range(1, 8):
tree.insert(k)
report(tree, f"insert {k}")
for k in [1, 1, 4, 9]:
found, depth = tree.search(k)
report(tree, f"search {k}")
print(f"{'':<12} found: {found}, depth before splay: {depth}")#include <algorithm>
#include <cstdio>
#include <memory>
#include <string>
#include <utility>
#include <vector>
struct Node {
int key;
Node* left = nullptr;
Node* right = nullptr;
Node* parent = nullptr;
explicit Node(int k) : key(k) {}
};
struct SplayTree {
Node* root = nullptr;
std::vector<std::string> steps;
std::vector<std::unique_ptr<Node>> owned;
void rotate(Node* x) {
// Lift x above its parent p, keeping the in-order sequence unchanged.
Node* p = x->parent;
Node* g = p->parent;
if (p->left == x) {
p->left = x->right;
if (x->right) x->right->parent = p;
x->right = p;
} else {
p->right = x->left;
if (x->left) x->left->parent = p;
x->left = p;
}
p->parent = x;
x->parent = g;
if (!g) {
root = x;
} else if (g->left == p) {
g->left = x;
} else {
g->right = x;
}
}
void splay(Node* x) {
while (x->parent) {
Node* p = x->parent;
Node* g = p->parent;
std::string k = std::to_string(x->key);
if (!g) {
steps.push_back("zig(" + k + ")");
rotate(x);
} else if ((g->left == p) == (p->left == x)) {
steps.push_back("zig-zig(" + k + ")");
rotate(p);
rotate(x);
} else {
steps.push_back("zig-zag(" + k + ")");
rotate(x);
rotate(x);
}
}
}
void insert(int key) {
Node* parent = nullptr;
Node* node = root;
while (node) {
parent = node;
node = key < node->key ? node->left : node->right;
}
owned.push_back(std::make_unique<Node>(key));
Node* x = owned.back().get();
x->parent = parent;
if (!parent) {
root = x;
} else if (key < parent->key) {
parent->left = x;
} else {
parent->right = x;
}
splay(x);
}
// Returns (found, depth of the last node visited before splaying).
std::pair<bool, int> search(int key) {
Node* node = root;
Node* last = nullptr;
int depth = -1;
while (node) {
last = node;
depth++;
if (key == node->key) break;
node = key < node->key ? node->left : node->right;
}
if (last) splay(last);
return {node != nullptr, depth};
}
void walk(Node* n, std::string& out) const {
if (!n) return;
if (!out.empty()) out += " ";
out += std::to_string(n->key);
walk(n->left, out);
walk(n->right, out);
}
std::string preorder() const {
std::string out;
walk(root, out);
return out;
}
};
int height(Node* n) { return n ? 1 + std::max(height(n->left), height(n->right)) : -1; }
void report(SplayTree& tree, const std::string& label) {
std::string steps;
for (size_t i = 0; i < tree.steps.size(); i++) steps += (i ? ", " : "") + tree.steps[i];
if (steps.empty()) steps = "none";
std::printf("%-12s rotations: %s\n", label.c_str(), steps.c_str());
std::printf("%-12s preorder: %s (height %d)\n", "", tree.preorder().c_str(), height(tree.root));
tree.steps.clear();
}
int main() {
SplayTree tree;
for (int k = 1; k <= 7; k++) {
tree.insert(k);
report(tree, "insert " + std::to_string(k));
}
for (int k : {1, 1, 4, 9}) {
auto [found, depth] = tree.search(k);
report(tree, "search " + std::to_string(k));
std::printf("%-12s found: %s, depth before splay: %d\n", "", found ? "True" : "False", depth);
}
return 0;
}import java.util.ArrayList;
import java.util.List;
public class Main {
static class Node {
int key;
Node left, right, parent;
Node(int key) {
this.key = key;
}
}
static class SplayTree {
Node root;
List<String> steps = new ArrayList<>();
void rotate(Node x) {
// Lift x above its parent p, keeping the in-order sequence unchanged.
Node p = x.parent;
Node g = p.parent;
if (p.left == x) {
p.left = x.right;
if (x.right != null) x.right.parent = p;
x.right = p;
} else {
p.right = x.left;
if (x.left != null) x.left.parent = p;
x.left = p;
}
p.parent = x;
x.parent = g;
if (g == null) {
root = x;
} else if (g.left == p) {
g.left = x;
} else {
g.right = x;
}
}
void splay(Node x) {
while (x.parent != null) {
Node p = x.parent;
Node g = p.parent;
if (g == null) {
steps.add("zig(" + x.key + ")");
rotate(x);
} else if ((g.left == p) == (p.left == x)) {
steps.add("zig-zig(" + x.key + ")");
rotate(p);
rotate(x);
} else {
steps.add("zig-zag(" + x.key + ")");
rotate(x);
rotate(x);
}
}
}
void insert(int key) {
Node parent = null, node = root;
while (node != null) {
parent = node;
node = key < node.key ? node.left : node.right;
}
Node x = new Node(key);
x.parent = parent;
if (parent == null) {
root = x;
} else if (key < parent.key) {
parent.left = x;
} else {
parent.right = x;
}
splay(x);
}
// Returns {found ? 1 : 0, depth of the last node visited before splaying}.
int[] search(int key) {
Node node = root, last = null;
int depth = -1;
while (node != null) {
last = node;
depth++;
if (key == node.key) break;
node = key < node.key ? node.left : node.right;
}
if (last != null) splay(last);
return new int[] {node != null ? 1 : 0, depth};
}
void walk(Node n, List<String> out) {
if (n == null) return;
out.add(String.valueOf(n.key));
walk(n.left, out);
walk(n.right, out);
}
String preorder() {
List<String> out = new ArrayList<>();
walk(root, out);
return String.join(" ", out);
}
}
static int height(Node n) {
return n == null ? -1 : 1 + Math.max(height(n.left), height(n.right));
}
static void report(SplayTree tree, String label) {
String steps = tree.steps.isEmpty() ? "none" : String.join(", ", tree.steps);
System.out.printf("%-12s rotations: %s%n", label, steps);
System.out.printf("%-12s preorder: %s (height %d)%n", "", tree.preorder(), height(tree.root));
tree.steps.clear();
}
public static void main(String[] args) {
SplayTree tree = new SplayTree();
for (int k = 1; k <= 7; k++) {
tree.insert(k);
report(tree, "insert " + k);
}
for (int k : new int[] {1, 1, 4, 9}) {
int[] r = tree.search(k);
report(tree, "search " + k);
System.out.printf("%-12s found: %s, depth before splay: %d%n", "", r[0] == 1 ? "True" : "False", r[1]);
}
}
}Step through it
Running on insert 1..7 in order, then search 1, 1, 4, 9
Worked Example: Sorted Inserts
The listing inserts 1, 2, …, 7 in order and then searches 1, 1, 4 and 9. Sorted inserts are the worst case for shape: each new key is zigged to the root and the tree becomes a left path of height 6.
Searching 1 walks all 6 edges, then splays 1 with three zig-zig steps. The height drops to 4, and the nodes that were deep are now much shallower. The second search for 1 finds it at the root with no rotations. Searching 4 takes one zig-zag. Searching 9 misses, splays the last node 7 with a zig-zig, and the height grows to 5: a single operation may make the shape worse.
- The cheap inserts built up the potential that the expensive search spent
- Total work stays O(log n) per operation over the whole sequence
Why Operations Are O(log n) Amortized
The bound comes from the potential method of amortized analysis. Give each node a rank r(x) = log₂(size of x's subtree), and let the potential be Φ = Σ r(x) over all nodes. A long path has high potential; a balanced tree has low potential.
The access lemma states that splaying x in a tree with root t has amortized cost at most 3(r(t) − r(x)) + 1 = O(log n). Zig-zig and zig-zag steps each cost at most 3(r′(x) − r(x)), and these telescope along the path; only the final zig adds the +1. So every search, insert and delete is O(log n) amortized, and m operations take O(m log n + n log n) in total.
A single operation can still cost O(n), as the first search in the example shows. Space is O(n) with no balance field per node.
- Static optimality: within a constant factor of the best fixed BST for the access frequencies
- Working-set property: accessing a key used t distinct keys ago costs O(log t) amortized
- Sequential access: visiting all keys in order costs O(n) in total
Splay Tree vs AVL Tree vs Red-Black Tree
All three are binary search trees with logarithmic operations, but they get there differently. AVL and red-black trees keep the tree balanced at all times, so every single operation is O(log n) in the worst case. A splay tree lets the shape drift and relies on amortization instead.
| Property | Splay tree | AVL tree | Red-black tree |
|---|---|---|---|
| Bound | O(log n) amortized | O(log n) worst case | O(log n) worst case |
| Extra field per node | none | height or balance factor | one colour bit |
| Height | can reach n − 1 | ≤ 1.44 log₂ n | ≤ 2 log₂ n |
| Search modifies the tree | yes, every access rotates | no | no |
| Adapts to access pattern | yes: hot keys near the root | no | no |
| Typical use | caches, ropes, skewed access | read-heavy lookups | language libraries (map, TreeMap) |
- Pick a splay tree when a few keys are accessed far more than the rest
- Pick AVL or red-black when every single operation must be fast, or reads are concurrent
Strengths and Weaknesses
This is the simplest balanced-in-effect BST to write: one splay routine and ordinary BST code. The price is that the bound only holds over sequences, and that reads also write.
- Strength: no balance data stored in nodes, and one splay routine does all the balancing
- Strength: frequently accessed keys become fast to reach; near-optimal on skewed and sequential access
- Strength: split and join are easy and O(log n) amortized
- Weakness: a single operation can take O(n), and height can reach n − 1 after sorted inserts
- Weakness: every search rotates nodes, so reads are not read-only and threads need locking
- Weakness: more rotations than AVL or red-black trees on uniform random access
- Recursive splay code can overflow the stack on a path of length n; use the iterative form
Where They Are Used
They suit problems where access is uneven or where sequences are split and joined often.
- Caches: recently used entries stay near the root, a natural fit for LRU-like behaviour
- Ropes and text editors: split and join make cutting and pasting long strings cheap
- Link-cut trees: Sleator and Tarjan's dynamic-tree structure uses splay trees for its paths, giving O(log n) amortized network-flow and connectivity operations
- Data compression: splay-tree based prefix codes adapt as symbol frequencies change
- Systems code: GCC's libiberty and the FreeBSD kernel's virtual memory map have used them for skewed lookups
- Practise the underlying BST moves: Delete Node in a BST