Treaps, skip lists and splay trees
Balance without color rules through randomized treaps and skip lists or self-adjusting splay trees. Prove the access lemma, examine working-set and dynamic-optimality results, and introduce persistence by path copying.
After this lesson you can
- Implement a treap with split and merge and prove logarithmic expected depth.
- Analyze skip-list height and space with high probability.
- Prove the splay-tree access lemma using the potential method.
- Explain working-set and static-finger properties and the dynamic optimality conjecture.
- Implement a persistent tree by path copying and measure its overhead.
Before you start
Motivation: balancing without special cases
A red–black tree guarantees worst-case height , at the cost of fragile logic: insertion has three cases plus their mirrors, deletion has more, and an error may gradually worsen height or corrupt the tree much later instead of breaking the program immediately. Each insertion can also recolor an entire path to the root, making it difficult to share the tree across threads.
This lesson presents two ways to balance without color rules, both more useful than they first appear:
- Randomize. Treaps and skip lists flip coins on insertion. Structure shape depends on those choices rather than key arrival order, so no insertion order, however bad, produces a degenerate tree except with negligible probability. Analysis follows randomized quicksort, and implementation fits in twenty lines with primitives
splitandmerge, also providing concatenation, set union and sequences with reversed ranges. - Self-adjust. A splay tree stores no balance information. Each key access raises it to the root using specific rotations. An individual operation may cost , but any sequence of operations costs , and the tree learns access patterns: if a few keys dominate accesses or accesses have temporal locality, cost falls below without instruction. Whether any search tree, even knowing the sequence beforehand, can serve some sequence more than a constant factor better is a major open problem in data structures.
Finally, a third idea changes the question: instead of modifying the tree, create a new version sharing almost everything with the old one. This is persistence, underlying git, immutable maps in functional languages and some transactional databases.
What follows uses the preceding lesson’s binary search tree and rotation vocabulary. Recall that a rotation raises a node one level and lowers its parent, preserves in-order traversal and costs .
Treaps: a search tree that is also a heap
It is not obvious that both orders can hold: search order governs horizontally (left and right), heap order vertically (up and down). The first result says it is possible and leaves no freedom.
Proof
Induct on pair count. With zero pairs the empty tree is unique. With , heap order forces the minimum-priority pair, say , to be the root; distinct priorities make it unique. Search order places exactly the pairs with keys less than in the left subtree and greater keys in the right. Each is a treap with fewer pairs, determined by induction. Conversely, root with those treaps as children satisfies both orders, so the treap exists.
∎The proof is also an algorithm, with a consequence underlying the analysis. Insert keys into an ordinary BST without rotations in increasing priority order: the first is the root, each lands in its proper subtree, and the result satisfies both orders. By uniqueness, it is the treap.
With continuous iid priorities, their order is a uniform permutation and shape depends only on it. The second sentence distinguishes treaps from ordinary BSTs: a random BST is good when data arrives randomly; a treap is good always, because it supplies the randomness. The sole assumption is that whoever chooses keys cannot see priorities.
To insert, descend as in any BST and attach the new node as a leaf. Search order holds, but heap order may fail on the parent edge. Repair with rotations: while the node’s priority is below its parent’s, rotate it upward. Each rotation preserves search order and moves the violation one level up, like heap sift-up. To delete, reverse the process: rotate the node down, always with the lower-priority child, until it is a leaf, then remove it.
How many rotations does insertion cost? In the worst case, as many as its depth. On average fewer than two, with an elegant argument: each rotation raising adds a node to the right spine of its left subtree (the path descending from its left child always to the right) or the left spine of its right subtree. Rotation count is therefore the sum of those spine lengths in the final treap.
Proof
Key with lies on the right spine of the left subtree of exactly when, among keys , the lowest priority belongs to and the second-lowest to . If were not lowest, an intermediate key or would be above it and would not descend from ; if any among had priority lower than , it would lie between and on the path and would lie to its left, off the spine. With keys, all priority orders are equally likely and the probability of those two particular positions is . Summing and telescoping,
The right side is symmetric, with instead of .
∎This matters: a rotation writes memory, and writes are expensive in concurrent or persistent structures. A treap restructures nodes on average per update, like a red–black tree (at most two rotations on insertion and three on deletion, though it may recolor an entire path).
Expected depth
The key question is how many ancestors a key has. The next lemma turns it into a priority question without inspecting the tree.
Proof
Let be the keys between and inclusive, and the lowest-priority key of . Follow the path from root to . While no path node belongs to , every node’s key is below all of or above all, so and enter the same subtree and stay together. The first node of on the path is : in the subtree containing all of the root has lowest priority, and by heap order no node of can be above . If , key goes to one side of and to the other, so is not an ancestor of . If , then lies on the path to : it is an ancestor. If , is an ancestor of , not vice versa.
∎This is exactly randomized quicksort’s criterion: and are compared if and only if the first pivot chosen between them is one of the endpoints. A treap is literally quicksort’s recursion tree with pivots chosen by priority. With iid priorities, each key of is equally likely to be smallest, so . Summing with indicator variables:
You will prove the first equality in the final guided exercise. The bound follows from : (the second inequality is logarithm concavity). Average over using . In bits, : a treap is 39% deeper on average than a perfect tree, as measured below. A red–black tree has worst-case height , though average depth is usually close to .
With high probability
Expectation is insufficient for an index: you want no slow searches. This requires concentration, and a non-obvious property appears. Split the depth of into left and right ancestors, , with . Read priorities of in that order, starting with : by the lemma, exactly when the priority of is a new minimum of the sequence, a record. Record indicators of a continuous iid sequence are independent: whether position is a record depends only on where the minimum falls among the first , not the earlier relative order (a Rényi result proved by counting permutations). Thus is a sum of independent Bernoullis with mean , and likewise .
Proof
The upper-tail multiplicative Chernoff bound, , remains valid if is replaced by any upper bound (the proof only uses , increasing with ). With , and , the exponent is , so . Likewise for . If , one of the two is at least , giving . By the union bound over keys, .
∎Constant is very pessimistic: Devroye showed in 1986 that random BST height is with probability tending to 1. The result’s form matters: logarithmic average depth plus independence gives polynomially small tail bounds, enough to use a treap where a red–black tree would be used unless a deterministic guarantee is required.
Split and merge: two primitives for everything
The cleanest way to program a treap uses two recursive operations instead of explicit rotations:
- splits into two treaps: with keys below and with the rest.
- joins two treaps with every key in smaller than every key in .
merge chooses the root by comparing the two roots’ priorities: if wins, retain its left subtree and make its right subtree ; if wins, reverse the roles. split descends the search path for and at each node decides its side and which part of its child it keeps. Both traverse a tree path (merge, the right spine of and left spine of ), costing expected . Both preserve both orders: check this before reading the implementation and program it in the coding exercise.
Everything else takes two lines with them:
- Insert : and return .
- Delete : find its node and replace it with of its two children.
- Union of sets and : the lower-priority root, say from , splits by its key, then recurse on each side. Blelloch and Reid-Miller (1998) showed union, intersection and difference of treaps of sizes cost expected , optimal, with independent recursions that parallelize naturally.
With split and merge by position, a sequence supports expected insertion or deletion anywhere, cutting and pasting ranges, concatenation, and with a lazy flag, reversing a whole range: split it out, mark its root “reversed” and merge again. The flag propagates to children (swapping them) only when an operation descends through the node. This is natural for a text editor (rope) or sequence problems with range operations; you will build it below.
Skip lists: lists with express lanes
Searching a sorted linked list costs . Pugh’s idea (1990) is to add express lanes: a second list with about half the nodes, a third with a quarter, and so on. Search descends a staircase: advance along the highest lane without overshooting, then drop a lane when the next node is too large.
To search , start at the header at level . At each level advance while the next key is less than ; otherwise descend a level. At level 1 the next node is or it is absent. Insertion searches while remembering the last node visited at each level (predecessors), draws the new key’s level and links it on those levels; deletion unlinks it. No rotations or rebalancing: random levels do the work.
Analyze the three quantities that matter using familiar tools.
Proof
(1) Each key contributes pointers and ; sum by linearity.
(2) if and only if some key has level at least , each with probability : by the union bound, . If , then and the bound is . For expectation, because .
(3) Backward analysis. Traverse the search path backwards from the last node visited at level 1. When at a node at level , its level is at least ; the forward path arrived by descending from level if the node’s level exceeds , or by advancing from the left otherwise. Conditioned on everything seen, the node’s level exceeds with probability : each backward step rises with probability (or 1 at the header) and otherwise moves left. Expected steps to accumulate ascents are at most , a negative binomial expectation. Above level remain at most ascents, with expectation by (2), and leftward moves through nodes of level at least , of which exist on average. Sum to obtain .
∎The dominant cost term is . Function peaks at , minimizing steps there: . But the maximum is flat: and give exactly because . For pointers, uses per key versus . Thus Pugh recommended , as measured in the implementation section. Search cost is also concentrated: steps to accumulate ascents exceed only if a binomial falls below , and Chernoff’s lower tail makes this probability polynomially small for with constant .
Why concurrent systems favor them. Skip-list insertion changes only the new key’s predecessor pointers, on average; no rotations reorganize entire subtrees and no recoloring climbs to the root. Level 1 is authoritative and higher levels are shortcuts: a search encountering a half-built shortcut remains correct because it can descend to level 1. This permits lock-free versions linking each level with atomic compare-and-swap (Fraser, 2004; Herlihy and Shavit develop this in The Art of Multiprocessor Programming). In practice Java ConcurrentSkipListMap is a lock-free skip list; LevelDB and RocksDB’s memtable, accumulating recent writes before disk flush, is a skip list; Redis sorted sets (ZADD, ZRANGE) combine a skip list and hash table beyond a few elements.
Splay trees: trees that reorganize on reads
A splay tree (Sleator and Tarjan, 1985) is a BST with no balance field, where every operation ends by raising the last node touched to the root using . While is not the root, let be its parent and its grandparent:
- zig: if is root, rotate with . This occurs only at the last step.
- zig-zig: if and are both left children (or both right), first rotate with , then with .
- zig-zag: if is a left child and right, or vice versa, rotate with , then with .
Search by descending to (or the last path node if absent) and splaying it. Insert by attaching and splaying the leaf. Delete by splaying , removing the root and joining the subtrees: splay the left maximum, now root without a right child, and attach the right subtree.
Zig-zag is the obvious move: two rotations of . Zig-zig changes everything. The obvious alternative, rotate to root (raise through single parent rotations, proposed by Allen and Munro in 1978), also brings to the root but leaves most of the path intact. Zig-zig folds the path onto itself and roughly halves the depth of all nodes on the access path. The figure compares both methods.
Single rotations admit sequences costing per access indefinitely: in the figure’s path, traversing keys in order costs nodes per pass, leaving the tree unchanged each time. A particular splay operation can also cost (the first access to 1 traverses all 15 nodes), but this cannot repeat indefinitely: amortized analysis makes that a theorem.
The access lemma
The analysis uses the potential method with a potential measuring tree imbalance. Assign each key an arbitrary weight (the algorithm neither knows nor uses it: it is an analysis tool) and define
is weighted subtree size and its rank. A path has high potential (many large subtrees) and a balanced tree low potential: with unit weights, of the 15-key path is versus about for a perfect tree. Actual splay cost is the number of rotations (or 1 if is already root), and amortized cost adds the potential increase.
The proof analyzes each step separately and sums. Below, and are ranks before and after a step. Only rotating-node ranks change, and the rank of afterward is the previous top rank: after zig-zig or zig-zag, . The only tool is a concavity inequality.
Proof
By the arithmetic–geometric mean inequality, . Set .
∎Proof
Access lemma, step by step. It suffices to prove amortized zig cost at most and zig-zig or zig-zag cost at most . Summing all steps telescopes terms to , appears once because only the final step can be zig, and ultimately is root with because total weight is unchanged.
Zig (one rotation, cost 1). Only and change, with , so . Since ends below , , and amortized cost is because .
Zig-zag (two rotations, cost 2). With , . Since was above , and . Afterward and are the two children of with disjoint subtrees, so and by concavity . Amortized cost is .
Zig-zig (two rotations, cost 2). This distinguishes splay from rotate-to-root; you will prove it in the final guided exercise using the same concavity lemma on another pair of disjoint subtrees.
∎The theorem’s 3 comes from zig-zig; zig-zag needs only 2. The argument also shows why single rotations fail: in a “rotate twice” step on a straight path, the lemma’s disjoint subtrees do not exist, and potential may not decrease despite paying for two rotations. The figure showed this: fourteen rotations with .
Proof
With unit weights, and , so each splay costs at most amortized. Total actual cost is total amortized cost minus and, since , the difference is bounded by .
∎Insertion and deletion are also amortized . Attaching a new leaf increases its ancestors’ sizes (bottom-up) by one; since , potential rises by at most (a telescoping sum, with and ). The subsequent splay pays the rest.
What splay learns without being told
The access lemma holds for any weight assignment, and the algorithm does not depend on weights. Thus the same splay tree simultaneously satisfies all bounds obtained by choosing different analysis weights. For an access sequence , total cost is at most
where the second term bounds potential decrease ( initially and finally). Each choice of weights gives a theorem:
- Static optimality. If key is accessed times, with cost is , where is frequency entropy. Any static BST costs at least because each search is a sequence of three-outcome comparisons (less, equal, greater) and the ternary-code entropy bound applies. Thus splay is as good up to constants as the optimal static BST built knowing frequencies in advance, without knowing them.
- Static finger. With for fixed key , and cost is : accessing near a finger is cheap, regardless of which finger.
- Working set. Let count distinct keys accessed since the last access to . Cost is . The proof uses time-varying weights, if is the -th most recent key; after accessing its weight becomes 1 and the more recent keys move down one rank, and this adjustment does not increase potential. This is the stack distance of an LRU cache: a splay tree behaves like a cache without having one.
- Sequential access. Accessing all keys in order costs total (Tarjan, 1985), constant amortized, even if each access starts far from the root.
- Dynamic finger. Stronger than static finger: cost is . Cole and coauthors proved it in 2000 in two papers and dozens of pages, not as a consequence of the access lemma.
The figure shows both sides. With structure (unequal frequencies, temporal locality, ordered traversals), splay exploits it without parameters or statistics. Without it, there is a constant cost: uniform accesses traverse about 30% more nodes than the fixed red–black tree shown (and 10% more than the deeper fixed treap in the splay cell), and each access writes as many rotations as nodes traversed minus one. In practice splay trees are mainly used with strong locality and one thread: FreeBSD organizes each process’s virtual-memory map entries in a splay tree, and GNU’s libiberty library used by GCC includes one.
The dynamic optimality conjecture
The bounds above compare splay with particular strategies. The ambitious question is whether it compares with all of them. Fix the BST model: to serve access to , an algorithm touches a connected subtree containing the root and , pays one unit per node touched and may reorganize those nodes into any BST. Let be the minimum cost of any algorithm in that model knowing the whole sequence in advance.
Open since 1985, it is probably the best-known open problem in data structures. Splay is immediately -competitive when starting from a balanced tree with potential : it costs and . Progress has followed three routes:
- Lower bounds for OPT. Wilber (1989) gave two computable lower bounds on . The difficulty is there: proving near-optimality requires knowing the optimum’s cost, and there is no formula.
- Nearly optimal trees. Tango trees (Demaine, Harmon, Iacono and Pătraşcu, 2004) are -competitive, the first result below . They use Wilber’s first bound and maintain a reference tree’s “preferred paths” as auxiliary trees.
- Problem geometry. Demaine, Harmon, Iacono, Kane and Pătraşcu (2009) showed that executing a BST algorithm corresponds to planar points (node touched, time) with a simple “arborally satisfied” combinatorial property, and is, up to a constant factor, the smallest satisfied superset of access points. This language yields a greedy algorithm, Greedy (Lucas, 1988; Munro, 2000), also conjectured optimal and satisfying many splay properties.
Iacono (2013) surveys the state of the problem. It illustrates an open question with publishable partial results: special cases of the conjecture (for example, sequences avoiding certain patterns) continue to appear at leading conferences.
Persistence: versions that do not overwrite each other
All preceding structures are ephemeral: an update destroys the previous state. Sometimes it must be retained for undo, historical queries, consistent transaction snapshots or lock-free sharing between threads, since immutable data needs no protection from changes.
The naive method, copying the entire structure on each update, costs per operation. The basic tree technique, path copying, observes that an update changes only nodes on the path from root to modification. Copy those nodes, point the copies at unchanged subtrees (shared with the old version), and use the copied root for the new version. In a tree of height , each update creates nodes, and old versions remain intact because no existing node is modified.
Path copying combines well with treaps (split and merge recurse along one path, so create nodes instead of modifying them) and red–black trees (rebalancing touches nodes near the path). To reduce space below per update, Driscoll, Sarnak, Sleator and Tarjan (1989) proposed two general techniques. With fat nodes, each field stores history as (version, value) pairs and a query in version finds the last value written in a version at most , at a factor in access time. With node copying, each node has a few spare modification fields and is copied only when they fill; for bounded in-degree structures this gives partial persistence with extra amortized space and time per modification. A classic application is Sarnak and Tarjan’s (1986) planar point location: a sweep with a persistent search tree gives per query using space.
Outside textbooks the idea is everywhere:
- git. A commit points to a directory tree, each directory to entries and each file to content, all identified by content hash. Changing a file creates a new object for it, one per directory on the path to root, and a new commit: path copying in a Merkle graph, with everything else shared across versions (used in git for research).
- Functional languages. Clojure and Scala vectors and maps and JavaScript immutable libraries use width-32 tries with path copying, so a “modification” creates about nodes. Haskell
Data.Mapis a size-balanced tree using the same technique. - Databases and file systems. LMDB stores data in a copy-on-write B+tree: a transaction copies the path of pages it modifies and commit atomically changes the root, so readers always see a consistent snapshot without blocking anyone. Btrfs uses the same idea for snapshots.
Implementation from scratch
Start with a treap using split and merge. Both functions reuse nodes (they are destructive), usual for an ephemeral structure. Check both orders and measure average depth for random and increasing insertion orders, the latter an unbalanced BST’s worst case.
import random, math
class Nodo:
__slots__ = ("clave", "pri", "izq", "der")
def __init__(self, clave, pri):
self.clave, self.pri = clave, pri
self.izq = self.der = None
def split(t, a):
"""Parte t en (claves < a, claves >= a). Reutiliza los nodos: t deja de ser válido."""
if t is None:
return None, None
if t.clave < a:
t.der, r = split(t.der, a)
return t, r
l, t.izq = split(t.izq, a)
return l, t
def merge(l, r):
"""Une dos treaps con todas las claves de l menores que todas las de r."""
if l is None or r is None:
return l or r
if l.pri < r.pri: # montículo de mínimo: la menor prioridad es la raíz
l.der = merge(l.der, r)
return l
r.izq = merge(l, r.izq)
return r
def insertar(t, clave, rnd=random.random):
l, r = split(t, clave)
return merge(merge(l, Nodo(clave, rnd())), r)
def borrar(t, clave):
if t is None:
return None
if clave == t.clave:
return merge(t.izq, t.der)
if clave < t.clave:
t.izq = borrar(t.izq, clave)
else:
t.der = borrar(t.der, clave)
return t
def recorrer(t, prof=0):
"""Genera (clave, prioridad, profundidad) en orden simétrico."""
if t is not None:
yield from recorrer(t.izq, prof + 1)
yield t.clave, t.pri, prof
yield from recorrer(t.der, prof + 1)
def es_treap(t, lo=-math.inf, hi=math.inf):
"""Orden de búsqueda (claves dentro de (lo, hi)) y orden de montículo."""
if t is None:
return True
if not (lo < t.clave < hi):
return False
for h in (t.izq, t.der):
if h is not None and h.pri < t.pri:
return False
return es_treap(t.izq, lo, t.clave) and es_treap(t.der, t.clave, hi)
def H(n):
return sum(1 / i for i in range(1, n + 1))
random.seed(1)
n = 2000
for nombre, orden in [("orden aleatorio", random.sample(range(n), n)), ("orden creciente", list(range(n)))]:
medias, alturas = [], []
for rep in range(10):
t = None
for c in orden:
t = insertar(t, c)
prof = [p for _, _, p in recorrer(t)]
medias.append(sum(prof) / n)
alturas.append(max(prof))
print(f"{nombre:16s} profundidad media {sum(medias) / 10:.2f} altura media {sum(alturas) / 10:.1f} treap válido: {es_treap(t)}")
print(f"teoría: 2(1 + 1/n)H_n - 4 = {2 * (1 + 1 / n) * H(n) - 4:.2f} 2 ln n = {2 * math.log(n):.2f} log2 n = {math.log2(n):.2f}")
for c in range(0, n, 2):
t = borrar(t, c)
claves = [c for c, _, _ in recorrer(t)]
print("tras borrar las pares:", len(claves), "claves; ordenadas:", claves == list(range(1, n, 2)), " treap válido:", es_treap(t))With , measured average depths (12.23 and 12.28, averaged over ten treaps) agree with theory, 12.36, and are the same for increasing keys: an unbalanced BST in that order would be a path of average depth 999.5. Height, about 23.5, is and far from pessimistic bound ; Devroye’s constant gives , reached only asymptotically.
Now the implicit treap: the key is position, each node stores subtree size and a lazy reversal flag. Check it against a Python list over thousands of random operations.
import random
class NodoS:
__slots__ = ("val", "pri", "tam", "inv", "izq", "der")
def __init__(self, val):
self.val, self.pri, self.tam, self.inv = val, random.random(), 1, False
self.izq = self.der = None
def tam(t):
return t.tam if t else 0
def empujar(t):
"""Aplica la inversión pendiente de t: intercambia sus hijos y les pasa la marca."""
if t is not None and t.inv:
t.izq, t.der = t.der, t.izq
for h in (t.izq, t.der):
if h is not None:
h.inv = not h.inv
t.inv = False
def actualizar(t):
t.tam = 1 + tam(t.izq) + tam(t.der)
def split_pos(t, k):
"""(los k primeros elementos, el resto)."""
if t is None:
return None, None
empujar(t)
if tam(t.izq) < k:
t.der, r = split_pos(t.der, k - tam(t.izq) - 1)
actualizar(t)
return t, r
l, t.izq = split_pos(t.izq, k)
actualizar(t)
return l, t
def merge_s(l, r):
if l is None or r is None:
return l or r
if l.pri < r.pri:
empujar(l)
l.der = merge_s(l.der, r)
actualizar(l)
return l
empujar(r)
r.izq = merge_s(l, r.izq)
actualizar(r)
return r
def insertar_en(t, i, val):
l, r = split_pos(t, i)
return merge_s(merge_s(l, NodoS(val)), r)
def borrar_en(t, i):
l, r = split_pos(t, i)
_, r = split_pos(r, 1)
return merge_s(l, r)
def invertir(t, i, j):
"""Invierte el tramo [i, j) en O(log n) esperado: solo se marca la raíz del tramo."""
l, r = split_pos(t, i)
m, r = split_pos(r, j - i)
if m is not None:
m.inv = not m.inv
return merge_s(merge_s(l, m), r)
def a_lista(t, out=None):
out = [] if out is None else out
if t is not None:
empujar(t)
a_lista(t.izq, out)
out.append(t.val)
a_lista(t.der, out)
return out
t = None
for ch in "treaps y splay trees":
t = insertar_en(t, tam(t), ch)
t = invertir(t, 0, 6)
t = invertir(t, 9, 14)
print("".join(a_lista(t)))
random.seed(3)
t, ref = None, []
for paso in range(3000):
op = random.random()
if op < 0.5 or not ref:
i, v = random.randint(0, len(ref)), random.randint(0, 99)
t = insertar_en(t, i, v); ref.insert(i, v)
elif op < 0.7:
i = random.randrange(len(ref))
t = borrar_en(t, i); del ref[i]
else:
i = random.randrange(len(ref)); j = random.randint(i, len(ref))
t = invertir(t, i, j); ref[i:j] = ref[i:j][::-1]
print("3000 operaciones aleatorias; coincide con la lista de Python:", a_lista(t) == ref, " longitud final:", len(ref))Notice where empujar is called: always before inspecting a node’s children. This is the same discipline as lazy propagation in the next lesson’s segment trees; forgetting it once causes bugs appearing only for particular operation sequences.
The splay tree uses parent pointers and counters for visited nodes and rotations. Compare it with a fixed treap (random-BST shape, not adaptive) across four access patterns, alongside frequency entropy and the working-set theorem’s average .
import random, math
from collections import Counter
class Splay:
"""Splay tree con punteros al padre. Cuenta nodos recorridos y rotaciones."""
class N:
__slots__ = ("k", "l", "r", "p")
def __init__(self, k):
self.k, self.l, self.r, self.p = k, None, None, None
def __init__(self):
self.raiz, self.rotaciones, self.recorridos = None, 0, 0
def _rotar(self, x):
p, g = x.p, x.p.p
if p.l is x:
p.l, x.r = x.r, p
if p.l: p.l.p = p
else:
p.r, x.l = x.l, p
if p.r: p.r.p = p
p.p, x.p = x, g
if g is None: self.raiz = x
elif g.l is p: g.l = x
else: g.r = x
self.rotaciones += 1
def _splay(self, x):
while x.p is not None:
p, g = x.p, x.p.p
if g is None:
self._rotar(x) # zig
elif (g.l is p) == (p.l is x):
self._rotar(p); self._rotar(x) # zig-zig: primero el padre
else:
self._rotar(x); self._rotar(x) # zig-zag
def buscar(self, k):
u, ultimo = self.raiz, None
while u is not None:
self.recorridos += 1
ultimo = u
if k == u.k: break
u = u.l if k < u.k else u.r
if ultimo is not None:
self._splay(ultimo) # también se ajusta si la clave no está
return u is not None
def insertar(self, k):
if self.raiz is None:
self.raiz = self.N(k); return
u = self.raiz
while True:
if k == u.k: break
v = u.l if k < u.k else u.r
if v is None:
v = self.N(k); v.p = u
if k < u.k: u.l = v
else: u.r = v
u = v; break
u = v
self._splay(u)
def secuencia(tipo, n, m, rnd):
perm = list(range(n)); rnd.shuffle(perm)
if tipo == "uniforme":
return [rnd.randrange(n) for _ in range(m)]
if tipo == "secuencial":
return [j % n for j in range(m)]
if tipo == "zipf 1.2":
pesos = [r ** -1.2 for r in range(1, n + 1)]
return [perm[r] for r in rnd.choices(range(n), weights=pesos, k=m)]
out = [] # conjunto de trabajo: 16 claves activas
for j in range(m): # que cambian cada 500 accesos
if j % 500 == 0:
activas = rnd.sample(range(n), 16)
out.append(rnd.choice(activas))
return out
def entropia(seq):
m = len(seq)
return -sum(c / m * math.log2(c / m) for c in Counter(seq).values())
def media_conjunto_trabajo(seq, n):
"""Media de log2(t + 1), con t = claves distintas desde el último acceso a la misma clave."""
ultimo, tot = {}, 0.0
for j, k in enumerate(seq):
t = len(set(seq[ultimo[k] + 1:j])) if k in ultimo else n
tot += math.log2(t + 1); ultimo[k] = j
return tot / len(seq)
rnd = random.Random(7)
n, m = 1023, 10000
estatico = None # un treap fijo como referencia (insertar y recorrer, de la primera celda)
for c in rnd.sample(range(n), n):
estatico = insertar(estatico, c, rnd.random)
prof = {c: p for c, _, p in recorrer(estatico)}
print(f"n = {n}, m = {m}, log2 n = {math.log2(n):.2f}")
print(f"{'patrón':12s} {'splay':>7s} {'rot/acc':>8s} {'treap fijo':>11s} {'H':>6s} {'log2(t+1)':>10s}")
for tipo in ["uniforme", "zipf 1.2", "secuencial", "trabajo 16"]:
seq = secuencia(tipo, n, m, rnd)
s = Splay()
for c in rnd.sample(range(n), n):
s.insertar(c)
s.rotaciones = s.recorridos = 0
for k in seq:
s.buscar(k)
fijo = sum(prof[k] + 1 for k in seq) / m
ws = f"{media_conjunto_trabajo(seq, n):10.2f}" if tipo == "trabajo 16" else f"{'·':>10s}"
print(f"{tipo:12s} {s.recorridos / m:7.2f} {s.rotaciones / m:8.2f} {fijo:11.2f} {entropia(seq):6.2f} {ws}")The table summarizes the previous section. With uniform accesses, splay visits about 12.4 nodes versus 11.3 for the fixed tree, losing while rotating about 11 times per access. With Zipf exponent 1.2, splay drops to 6.8 nodes, near entropy (6.1 bits), while the fixed tree stays at 11.9 because it does not know popular keys. Sequential access costs about 5.2 nodes per access, constant as the sequential-access theorem predicts. A 16-key working set costs 4.5 nodes, tracking average of 2.95 with a small constant, versus the fixed tree’s 11.2.
The skip list has instrumented search. Measure pointers per key and search steps for four values of (average of three lists each), then the height distribution across skip lists of 1,000 keys against the union bound. Heights do not require constructing lists: they are the maximum level.
import random, math
import numpy as np
import matplotlib.pyplot as plt
class SkipList:
"""Skip list con cabecera de nivel MAX. Cada nodo guarda su clave y sus punteros 'sig', uno por nivel."""
MAX = 40
class N:
__slots__ = ("k", "sig")
def __init__(self, k, niveles):
self.k, self.sig = k, [None] * niveles
def __init__(self, p, rnd):
self.p, self.rnd = p, rnd
self.cab = self.N(-math.inf, self.MAX)
self.altura = 1 # niveles en uso
self.punteros = 0
self.pasos = 0 # avances + bajadas de la última búsqueda
def _nivel(self):
l = 1
while l < self.MAX and self.rnd.random() < self.p:
l += 1
return l
def _predecesores(self, k):
"""Último nodo con clave < k en cada nivel, de arriba abajo, contando pasos."""
pred = [None] * self.MAX
u, pasos = self.cab, 0
for L in range(self.altura - 1, -1, -1):
while u.sig[L] is not None and u.sig[L].k < k:
u = u.sig[L]; pasos += 1
pred[L] = u
if L > 0:
pasos += 1 # bajada
self.pasos = pasos
return pred
def buscar(self, k):
x = self._predecesores(k)[0].sig[0]
return x is not None and x.k == k
def insertar(self, k):
pred = self._predecesores(k)
if pred[0].sig[0] is not None and pred[0].sig[0].k == k:
return
l = self._nivel()
for L in range(self.altura, l): # niveles nuevos: el predecesor es la cabecera
pred[L] = self.cab
self.altura = max(self.altura, l)
x = self.N(k, l)
for L in range(l):
x.sig[L], pred[L].sig[L] = pred[L].sig[L], x
self.punteros += l
rnd = random.Random(11)
n = 2048
print(f"n = {n}, media de 3 skip lists por cada p")
print(f"{'p':>6s} {'punteros/clave':>15s} {'1/(1-p)':>8s} {'pasos medios':>13s} {'cota L/p + 1/(1-p)':>19s} {'altura':>7s}")
for p in [1/2, 1/math.e, 1/4, 1/8]:
ptr = pasos = alt = 0
for rep in range(3):
s = SkipList(p, rnd)
claves = rnd.sample(range(10 * n), n)
for c in claves:
s.insertar(c)
for c in claves[:1000]:
assert s.buscar(c)
pasos += s.pasos / 3000
ptr += s.punteros / (3 * n)
alt += s.altura / 3
L = math.ceil(math.log(n) / math.log(1 / p))
print(f"{p:6.3f} {ptr:15.3f} {1 / (1 - p):8.3f} {pasos:13.2f} {L / p + 1 / (1 - p):19.2f} {alt:7.1f}")
# altura en 10^4 skip lists con n = 1000 y p = 1/2: la altura es el máximo de n niveles geométricos
gen = np.random.default_rng(0)
n, R = 1000, 10_000
alturas = np.concatenate([gen.geometric(0.5, size=(1000, n)).max(axis=1) for _ in range(R // 1000)])
hs = np.arange(8, 25)
medida = np.array([(alturas > h).mean() for h in hs])
exacta = 1 - (1 - 0.5 ** hs) ** n
union = np.minimum(1, n * 0.5 ** hs)
print(f"\naltura media {alturas.mean():.2f} (log2 n = {math.log2(n):.2f}), máxima observada {alturas.max()}")
for h, e, x, u in zip(hs, medida, exacta, union):
if h in (10, 12, 14, 16, 20):
print(f"P[H > {h:2d}]: medida {e:.4f} exacta {x:.4f} cota de la unión n·2^-h = {u:.4f}")
for c in (1, 2):
h = math.ceil((1 + c) * math.log2(n))
print(f"c = {c}: P[H > {h}] medida {(alturas > h).mean():.1e} <= 1/n^c = {1 / n**c:.1e}")
plt.figure(figsize=(6, 3.2))
plt.semilogy(hs, np.maximum(medida, 1e-5), "o", label="medida (10⁴ skip lists)")
plt.semilogy(hs, exacta, "-", label="exacta 1 − (1 − 2⁻ʰ)ⁿ")
plt.semilogy(hs, union, "--", label="cota de la unión n·2⁻ʰ")
plt.xlabel("h"); plt.ylabel("P[H > h]"); plt.ylim(1e-5, 1.5); plt.legend(); plt.tight_layout(); plt.show()Pointers per key match within about 1% or better, and measured steps stay below the bound in all four cases. The minimum is at , with very close; costs little more for 50% more pointers; with towers are so short horizontal moves begin to dominate. Average height with is 11.3, slightly above , and the tail matches theory: for union bound is almost exact because the events summed are nearly disjoint, and with measured frequency (0.0009) stays below .
Finally, persistence: a treap where split and insertion create new nodes rather than modifying existing ones (nodes are immutable). Count nodes created per version.
import random, math
from dataclasses import dataclass
@dataclass(frozen=True)
class P:
clave: int
pri: float
izq: "P | None" = None
der: "P | None" = None
creados = 0
def nodo(clave, pri, izq, der):
global creados
creados += 1
return P(clave, pri, izq, der)
def p_split(t, a):
"""Como split, pero sin tocar t: copia solo los nodos del camino."""
if t is None:
return None, None
if t.clave < a:
l, r = p_split(t.der, a)
return nodo(t.clave, t.pri, t.izq, l), r
l, r = p_split(t.izq, a)
return l, nodo(t.clave, t.pri, r, t.der)
def p_insertar(t, clave, pri):
"""Inserción persistente: baja hasta el nivel que le toca a la prioridad nueva y parte ahí."""
if t is None:
return nodo(clave, pri, None, None)
if pri < t.pri:
l, r = p_split(t, clave)
return nodo(clave, pri, l, r)
if clave < t.clave:
return nodo(t.clave, t.pri, p_insertar(t.izq, clave, pri), t.der)
return nodo(t.clave, t.pri, t.izq, p_insertar(t.der, clave, pri))
def claves(t):
return [] if t is None else claves(t.izq) + [t.clave] + claves(t.der)
def distintos(raices):
vistos, pila = set(), [r for r in raices if r is not None]
while pila:
u = pila.pop()
if id(u) in vistos:
continue
vistos.add(id(u))
pila.extend(h for h in (u.izq, u.der) if h is not None)
return len(vistos)
random.seed(5)
n = 4000
versiones = [None]
for c in random.sample(range(n), n):
versiones.append(p_insertar(versiones[-1], c, random.random()))
copia_entera = sum(range(n + 1))
print(f"{n} versiones: {creados} nodos creados, {distintos(versiones)} distintos alcanzables")
print(f"por inserción: {creados / n:.2f} nodos; 2 ln n = {2 * math.log(n):.2f}")
print(f"copiando la estructura entera en cada versión: {copia_entera:,} nodos ({copia_entera / creados:.0f} veces más)")
v10 = versiones[10]
print("la versión 10 sigue intacta:", len(claves(v10)) == 10 and claves(v10) == sorted(claves(v10)))Each insertion creates about 14.5 nodes: ancestors of the new node plus nodes cut by p_split, totaling a depth plus a constant. All 4,000 versions fit in about 58,000 nodes, 138 times fewer than copying each entire version, and version 10 remains exactly as it was.
In libraries and systems
Python’s standard library has no balanced search tree. The usual option is sortedcontainers, not a tree but a list of sorted lists of around a thousand elements: with modern caches this beats a pointer tree written in pure Python.
from sortedcontainers import SortedList # pip install sortedcontainers
s = SortedList([5, 1, 9, 3])
s.add(4)
s.bisect_left(4), s[2], list(s.irange(3, 6)) # rango en O(log n), acceso por posición
| Structure | Where it appears |
|---|---|
| Red–black | C++ std::map and std::set (libstdc++), Java TreeMap, Linux kernel (rbtree.h) |
| Skip list | Java ConcurrentSkipListMap, LevelDB and RocksDB memtables, Redis sorted sets |
| Treap and implicit treap | ropes and sequences in competitive programming; Blelloch and Reid-Miller’s parallel set union |
| Splay tree | FreeBSD virtual-memory map, GNU libiberty |
| Persistent | git, Clojure and Scala (path-copying tries), Haskell Data.Map, LMDB, Btrfs |
Selection is straightforward: for worst-case latency, red–black (or AVL); for concurrency, skip list; for sequence or set operations (cut, paste, union), treap; for highly local accesses without concurrency, splay; and for disk data or data too large for cache, the preceding lesson’s B-tree.
Common mistakes
Exercises
Step 1 of 4. What is ?
Step 1 of 3. How does simplify?
split(t, a), splitting treap t into (L, R) with keys in L below a and keys in R greater or equal, and merge(l, r), joining two treaps assuming every key in l is below every key in r. Nodes have fields clave, pri, izq and der; heap order is minimum (root has lowest priority). You may reuse nodes without copying. Tests check in-order traversal, heap order and logarithmic average depth of a treap built with your split and merge by inserting 2,000 keys in increasing order.class Nodo:
__slots__ = ("clave", "pri", "izq", "der")
def __init__(self, clave, pri):
self.clave, self.pri = clave, pri
self.izq = self.der = None
def split(t, a):
"""Devuelve (L, R): claves < a en L y claves >= a en R."""
# tu código
return t, None
def merge(l, r):
"""Une l y r; todas las claves de l son menores que las de r."""
# tu código
return l if l is not None else rSummary
- A treap is a BST on keys and heap on random priorities. Its unique shape is that of a randomly inserted BST: is an ancestor of if it has the interval’s lowest priority, expected depth is , and rotations per update average fewer than two.
splitandmergesuffice for insertion, deletion, set union and, with sizes and lazy flags, sequences with range reversal (implicit treap).- A skip list uses geometric levels: pointers, average height and height with high probability by the union bound, and about search steps by backward analysis. Local updates make it a leading concurrent ordered structure.
- A splay tree raises each accessed node to the root with zig, zig-zig (parent first) and zig-zag. With , the access lemma gives amortized ; choosing weights yields balance, static optimality, static finger and working-set bounds. Whether it is -competitive against any dynamic BST is the dynamic optimality conjecture, open since 1985.
- Path copying makes a tree persistent with new nodes per update; this underlies git, immutable maps and copy-on-write databases. Amortized bounds do not survive persistence.