Balanced search trees and B-trees
Binary search trees maintain ordered sets with search, insertion, predecessor and range queries. Study rotations, AVL and red–black trees as 2–3–4 trees, external-memory costs and optimal B-trees, and parameter-free cache-oblivious design.
After this lesson you can
- Implement binary search tree operations, including deletion by successor.
- Prove height bounds for AVL and red–black trees.
- Restore red–black invariants after insertion using the 2–3–4 tree correspondence.
- Analyze searching and sorting in the external-memory model and justify B-tree degree.
- Explain van Emde Boas layout as a cache-oblivious structure.
Before you start
Motivation: a changing ordered set
Most programs store a set of keys that grows and shrinks while being queried. If only membership and insertion matter, a hash table is hard to beat. Often, however, the question concerns order:
- Ordered maps. C++
std::map, JavaTreeMapor RustBTreeMap: iterate keys in order, ask for the greatest key below (predecessor) or smallest above (successor), or extract all in a range. - Database indexes.
WHERE fecha BETWEEN a AND borORDER BYwithout sorting the whole table: an index is an ordered set of keys with row pointers, stored on disk and updated on each insertion. - File systems. Large directories, free extents or metadata are stored in ordered disk structures.
- Scheduling and rankings. A scheduler asks for “the next event after ,” not just the minimum from a heap; an online ranking asks “how many players have fewer points than me?”; a sweep line maintains segments ordered by height.
Each structure you already know falls short on some of these questions:
| Structure | Search | Insert | Minimum | Successor | Range with results |
|---|---|---|---|---|---|
| Hash table | expected | amortized | |||
| Sorted array | |||||
| Binary heap | |||||
| Balanced search tree |
The last row is this lesson’s goal, with three threads. First, shape: what a search tree is, operation cost as a function of height, and why height needs monitoring (rotations change shape without changing order). Second, balance: AVL and red–black trees guarantee logarithmic height through local work, and red–black trees have a surprising correspondence with multiway trees. Third, memory: when data does not fit in RAM, counting comparisons misleads and block transfers matter. Binary trees cease to be optimal, B-trees appear, followed by design without knowing block size (cache-oblivious).
Binary search trees
Assume distinct keys; for duplicates, specify a tie-breaker. The ordering property is a local invariant that lets us discard half of what remains at each step, as in binary search, but on a modifiable structure.
All ordered-set operations reduce to descending a path, so they cost in the first lesson’s asymptotic notation:
- Search . Compare with the root: if smaller, go left; if larger, right. Reaching an empty child means is absent.
- Minimum and maximum. Always descend left (or right).
- Successor of . It is the minimum of the right subtree if present; otherwise the lowest ancestor from which descends left. Find it by descending from the root and remembering the last left turn.
- Insert . Search for and attach a new node at the empty child: it always enters as a leaf.
- Delete . Three cases: remove a leaf; replace a node with one child by that child. With two children, copy its successor key (the minimum of the right subtree, with no left child) and delete the successor, which falls into an easy case.
- Range . Perform pruned in-order traversal: do not descend left of a node with key or right of one with key . Every visited node is either inside the interval (at most ) or on one of the search paths for and (at most ), yielding cost .
- Rank and selection. If every node stores subtree size, count keys smaller than by adding left-subtree size whenever descending right (and, upon finding , its left-subtree size); find the key of rank by comparing with that size. Both take .
import math, random
class NodoBB:
__slots__ = ("k", "izq", "der")
def __init__(self, k):
self.k, self.izq, self.der = k, None, None
def insertar(raiz, k):
"""Inserta k de forma iterativa (sirve también para cadenas muy profundas) y devuelve la raíz."""
nuevo = NodoBB(k)
if raiz is None:
return nuevo
x = raiz
while True:
if k < x.k:
if x.izq is None:
x.izq = nuevo
return raiz
x = x.izq
elif k > x.k:
if x.der is None:
x.der = nuevo
return raiz
x = x.der
else:
return raiz # ya estaba
def minimo(x):
while x.izq is not None:
x = x.izq
return x
def sucesor(raiz, k):
"""Menor clave estrictamente mayor que k: baja desde la raíz recordando el último desvío a la izquierda."""
mejor, x = None, raiz
while x is not None:
if k < x.k:
mejor, x = x.k, x.izq
else:
x = x.der
return mejor
def borrar(x, k):
"""Borrado de Hibbard: con dos hijos, la clave del sucesor ocupa el lugar y el sucesor se borra."""
if x is None:
return None
if k < x.k:
x.izq = borrar(x.izq, k)
elif k > x.k:
x.der = borrar(x.der, k)
else:
if x.izq is None:
return x.der
if x.der is None:
return x.izq
x.k = minimo(x.der).k
x.der = borrar(x.der, x.k)
return x
def en_orden(x):
if x is not None:
yield from en_orden(x.izq)
yield x.k
yield from en_orden(x.der)
def estadisticas(raiz):
"""(altura, profundidad media de un nodo) con una pila, sin recursión."""
pila, total, n, alt = [(raiz, 0)], 0, 0, 0
while pila:
x, d = pila.pop()
if x is None:
continue
n += 1
total += d
alt = max(alt, d)
pila += [(x.izq, d + 1), (x.der, d + 1)]
return alt, total / n
# --- comprobación contra una lista ordenada ---
rnd = random.Random(0)
claves = rnd.sample(range(10**6), 2000)
raiz = None
for k in claves:
raiz = insertar(raiz, k)
assert list(en_orden(raiz)) == sorted(claves)
orden = sorted(claves)
assert all(sucesor(raiz, orden[i]) == orden[i + 1] for i in range(len(orden) - 1)) and sucesor(raiz, orden[-1]) is None
for k in rnd.sample(claves, 700):
raiz = borrar(raiz, k)
orden.remove(k)
assert list(en_orden(raiz)) == orden
print("operaciones correctas; quedan", len(orden), "claves")
# --- la forma depende del orden de inserción ---
n = 1000
H = sum(1 / j for j in range(1, n + 1))
alturas, medias = [], []
claves = list(range(n))
for _ in range(40):
rnd.shuffle(claves)
raiz = None
for k in claves:
raiz = insertar(raiz, k)
a, m = estadisticas(raiz)
alturas.append(a)
medias.append(m)
print(f"inserción aleatoria, n = {n}, 40 árboles: altura media {sum(alturas)/40:.1f}, profundidad media {sum(medias)/40:.2f}")
print(f" fórmula 2(n+1)H_n/n - 4 = {2 * (n + 1) * H / n - 4:.2f}; log2 n = {math.log2(n):.2f}; 2 ln n = {2 * math.log(n):.2f}")
raiz = None
for k in range(n):
raiz = insertar(raiz, k)
a, m = estadisticas(raiz)
print(f"inserción en orden, n = {n}: altura {a}, profundidad media {m:.1f}")How tall is an unbalanced tree?
If keys arrive in random order, the BST behaves well. This is the same situation as random-pivot quicksort: the root is a randomly chosen key, smaller keys form the left subtree and larger keys the right, and each subtree is again a random-insertion BST.
Proof
The root is the first inserted key, and its rank among the keys is uniform. This leaves keys on the left and on the right, each side a random BST of its size. Since each of the remaining nodes is one level deeper than in its own subtree,
This is the recurrence for expected quicksort comparisons. Solve it by subtracting the equation for from that for to eliminate the sum: , that is, . Dividing by gives and, since , it telescopes:
whence . Since , the average is .
∎A typical node is therefore 39% deeper than in a perfect tree (). The worst node is another story: expected height grows as with (Devroye, 1986; Reed, 2003 refines lower-order terms), about three for large . Still, it is logarithmic. The preceding cell measures 40 trees with : average depth 10.97, nearly the formula’s 10.99, and average height 21.0 (at these sizes the subtractive lower-order height terms matter greatly).
Rotations: change shape without changing order
The ordering invariant leaves enormous freedom: different BSTs have the same keys, and all are valid. Balancing moves between them with a cheap operation: rotation.
The check takes one line: in read and in read the same. Since in-order traversal does not change, every node has a fixed position in it. The first interactive shows this, placing each node in its in-order column: rotation can only move it up or down.
With 11 keys, global Day–Stout–Warren (DSW) balancing straightens the tree into a spine and compresses it in passes, requiring 8 rotations to reach minimum height from the chain. Inserting in order into an AVL costs 7 total, spread along the way. A later cell checks the general pattern: inserting in order into an AVL takes exactly rotations at every tested size, nearly one per key. Rotations are not free, but they are local: AVL and red–black trees need or fewer per update.
AVL trees
This local condition forces logarithmic height. To see why, ask what the thinnest AVL of a given height looks like.
The proof is the first of two guided exercises at the end. The idea: the thinnest tree has a root, a minimum subtree of height and another of height (balance allows the second to be one lower, no more), so , the Fibonacci linear recurrence shifted by one. Its solution grows as , and solving for gives the bound. Initial values are .
The table compares longest-path node counts for a perfect tree with keys, worst AVL height (largest with ), and worst red–black height (the same calculation on its thinnest trees), alongside the bound proved for the latter in the next section:
| Perfect | AVL worst case | Red–black worst case | Bound | |
|---|---|---|---|---|
| 10 | 14 | 17 | 19 | |
| 20 | 28 | 37 | 39 | |
| 30 | 42 | 57 | 59 |
Insertion into an AVL starts as in a BST. Returning toward the root, update heights and inspect each ancestor’s balance factor. Repair the first to reach (call it ) according to where the node landed:
- Outer case (heavy child of is heavy on the same side: left–left or right–right). One rotation on fixes it.
- Inner case (left–right or right–left). One rotation is insufficient, leaving the inner subtree on the already heavy side. Use a double rotation: first rotate with its child to turn it into an outer case, then .
Why does this work, and why is one repair enough? Let be the height of in the left–left case, . Before insertion was balanced, so had height at most . Inserting in grew to , so now ; since the prior height of was , , and since remains balanced, . After rotating right, : has two children of height , so height , and has two children of height , so height . That is exactly the height had before insertion (), so no ancestor notices: an insertion needs at most one repair (single or double rotation).
Deletion is worse. After deletion, the repaired subtree may be one unit shorter than before, unbalancing its parent and so on: up to rotations per deletion, one per level, in the worst case. Each rotation is , so total operation cost remains , but rotations lead many libraries to prefer red–black trees.
import math, random
class NodoAVL:
__slots__ = ("k", "izq", "der", "h")
def __init__(self, k):
self.k, self.izq, self.der, self.h = k, None, None, 0
def alt(x): return -1 if x is None else x.h
def act(x):
x.h = 1 + max(alt(x.izq), alt(x.der))
return x
contador = {"rotaciones": 0}
def rot_der(y):
x = y.izq
y.izq, x.der = x.der, y
contador["rotaciones"] += 1
act(y) # primero el que baja
return act(x) # después el que sube
def rot_izq(x):
y = x.der
x.der, y.izq = y.izq, x
contador["rotaciones"] += 1
act(x)
return act(y)
def insertar_avl(x, k):
if x is None:
return NodoAVL(k)
if k < x.k:
x.izq = insertar_avl(x.izq, k)
elif k > x.k:
x.der = insertar_avl(x.der, k)
else:
return x
act(x)
b = alt(x.izq) - alt(x.der)
if b > 1: # pesa a la izquierda
if alt(x.izq.izq) < alt(x.izq.der): # caso interior: rotación doble
x.izq = rot_izq(x.izq)
return rot_der(x)
if b < -1:
if alt(x.der.der) < alt(x.der.izq):
x.der = rot_der(x.der)
return rot_izq(x)
return x
def comprobar(x):
"""Devuelve (altura, nodos) y verifica orden y factores de equilibrio."""
if x is None:
return -1, 0
hi, ni = comprobar(x.izq)
hd, nd = comprobar(x.der)
assert abs(hi - hd) <= 1 and x.h == 1 + max(hi, hd), "no es AVL"
return x.h, ni + nd + 1
phi = (1 + 5 ** 0.5) / 2
rnd = random.Random(1)
print(" n rotaciones en orden n - ceil(log2(n+1)) altura en orden altura aleatoria cota log_phi(n+1) - 1")
for n in (7, 15, 100, 1000, 2000):
contador["rotaciones"] = 0
raiz = None
for k in range(n):
raiz = insertar_avl(raiz, k)
h_orden, _ = comprobar(raiz)
rot = contador["rotaciones"]
claves = list(range(n))
rnd.shuffle(claves)
raiz = None
for k in claves:
raiz = insertar_avl(raiz, k)
h_azar, _ = comprobar(raiz)
cota = math.log(n + 1, phi) - 1
assert h_orden <= cota and h_azar <= cota
assert rot == n - math.ceil(math.log2(n + 1))
print(f"{n:5d} {rot:10d} {n - math.ceil(math.log2(n + 1)):18d} {h_orden:14d} {h_azar:14d} {cota:14.2f}")
def delgado(h):
"""El AVL de altura h con menos nodos: raíz, un hijo delgado de altura h-1 y otro de altura h-2."""
if h < 0:
return None
x = NodoAVL(0)
x.izq, x.der = delgado(h - 1), delgado(h - 2)
return act(x)
fib = [0, 1]
for _ in range(20):
fib.append(fib[-1] + fib[-2])
print("\nh nodos del AVL delgado F_(h+3) - 1")
for h in range(0, 11):
_, nodos = comprobar(delgado(h))
assert nodos == fib[h + 3] - 1
print(f"{h:2d} {nodos:10d} {fib[h + 3] - 1:10d}")Red–black trees
AVL trees require strict height balance. Red–black trees relax it just enough to make updates cheaper, worsening the height bound from to in exchange.
The two bold rules matter most. The second says red nodes are isolated on any path: never two consecutively. The third says all paths have the same number of black nodes. Together they bound the disparity between longest and shortest paths: every root-to-empty-leaf path has the same black nodes, so at least nodes, and since every red node is directly below a black one (root is black and no two reds are adjacent), at most .
The classical proof, guided in the exercises, has two steps: a node’s subtree of black height contains at least nodes (by induction), and rule 2 makes at least half the nodes on any path black. But another view makes the reason immediately clear and explains more.
A red–black tree is a binary encoding of a 2–3–4 tree
Group each black node with any red children. Each group contains 1, 2 or 3 nodes and represents a multiway-tree node with 1, 2 or 3 keys, that is, 2, 3 or 4 children:
- black with no red children: a 2-node (one key);
- black with one red child (left or right: two representations): a 3-node (two keys);
- black with two red children: a 4-node (three keys).
A 2–3–4 tree (the minimum-degree-2 B-tree seen below) requires all leaves at the same depth. This is exactly rule 3: counting black nodes on a path counts 2–3–4 nodes traversed. Rule 2 prevents a group from having more than three keys. Thus red–black rules encode a 2–3–4 tree in binary, and the height bound follows: the 2–3–4 tree has depth and at least keys, and each node becomes at most two binary levels. Red nodes are the portion of a multiway node that does not fit in one binary node.
Insertion: three cases as B-tree operations
Insert a red node as in a BST. This never breaks rule 3 (black counts do not change) and breaks rule 2 only if the parent is red. Then the grandparent is black (a red parent cannot be root), and behavior depends on the uncle’s color, the parent’s sibling:
| Uncle | Red–black | 2–3–4 tree | What happens next |
|---|---|---|---|
| (parent is black) | no violation | key enters a node with fewer than 3 keys | nothing |
| red | parent and uncle become black, grandparent red | node already had 3 keys; a fourth overflows it, so split in two and promote the middle key | grandparent may have a red parent: repeat two levels up |
| black | one or two rotations and a color swap | three keys change binary shape | done: fixed without changes higher up |
Splits propagate toward the root only while the parent is full; if they reach it, the root splits and the tree grows upward by one level for all leaves at once. Rotations, by contrast, occur once and finish: insertion makes at most two rotations and, by a potential-method argument (potential counts three-key 2–3–4 nodes: each split removes one and insertion creates at most one), total splits, hence recolorings, in insertions is .
Deletion reverses this: remove a key from a 2–3–4 leaf and, if the node is empty, borrow one from a sibling through the parent (a rotation) or merge with a sibling by moving down the separator (recoloring). Merging may empty the parent and repeat upward. A red–black tree makes at most three rotations per deletion versus the AVL’s possible . Cormen et al.’s deletion rules have four cases with “double black”; in a 2–3–4 tree they are simply “borrow or merge.”
The left-leaning variant
Sedgewick (2008) simplified implementation with the left-leaning red–black tree (LLRB), requiring a canonical shape: red links may lean only left. A 3-node then has one representation, the tree corresponds to a 2–3 tree (three-key 4-nodes only transiently), and three local operations suffice after each insertion or deletion: rotate a right red link left, rotate two consecutive red links right, and flip colors of a node with two red children (splitting a 4-node). The next cell implements it fully, with deletion, range and rank; balancing and deletion functions occupy fewer than 100 lines. Simplicity has a price: canonical shape also forces rotations on the return to the root (each right red link left by a flip is rotated), so LLRB loses the classic red–black rotation bound per update and may make ; total cost remains . The verifier checks invariants after every operation and a randomized test compares with a sorted list.
import math, random, bisect
ROJO, NEGRO = True, False
class Nodo:
__slots__ = ("k", "izq", "der", "rojo", "n")
def __init__(self, k):
self.k, self.izq, self.der, self.rojo, self.n = k, None, None, ROJO, 1
def es_rojo(h): return h is not None and h.rojo
def tam(h): return 0 if h is None else h.n
def actualiza(h):
h.n = 1 + tam(h.izq) + tam(h.der)
return h
def rotar_izq(h):
x = h.der
h.der, x.izq = x.izq, h
x.rojo, h.rojo = h.rojo, ROJO
actualiza(h) # primero el que baja, después el que sube
return actualiza(x)
def rotar_der(h):
x = h.izq
h.izq, x.der = x.der, h
x.rojo, h.rojo = h.rojo, ROJO
actualiza(h)
return actualiza(x)
def voltear(h): # dividir un 4-nodo: la clave central sube
h.rojo = not h.rojo
h.izq.rojo = not h.izq.rojo
h.der.rojo = not h.der.rojo
def equilibrar(h):
if es_rojo(h.der) and not es_rojo(h.izq):
h = rotar_izq(h)
if es_rojo(h.izq) and es_rojo(h.izq.izq):
h = rotar_der(h)
if es_rojo(h.izq) and es_rojo(h.der):
voltear(h)
return actualiza(h)
def _insertar(h, k):
if h is None:
return Nodo(k)
if k < h.k:
h.izq = _insertar(h.izq, k)
elif k > h.k:
h.der = _insertar(h.der, k)
else:
return h
return equilibrar(h)
def _mover_rojo_izq(h): # presta un nodo rojo a la izquierda antes de bajar por ella
voltear(h)
if es_rojo(h.der.izq):
h.der = rotar_der(h.der)
h = rotar_izq(h)
voltear(h)
return h
def _mover_rojo_der(h):
voltear(h)
if es_rojo(h.izq.izq):
h = rotar_der(h)
voltear(h)
return h
def _minimo(h):
while h.izq is not None:
h = h.izq
return h
def _borrar_min(h):
if h.izq is None:
return None
if not es_rojo(h.izq) and not es_rojo(h.izq.izq):
h = _mover_rojo_izq(h)
h.izq = _borrar_min(h.izq)
return equilibrar(h)
def _borrar(h, k):
if k < h.k:
if not es_rojo(h.izq) and not es_rojo(h.izq.izq):
h = _mover_rojo_izq(h)
h.izq = _borrar(h.izq, k)
else:
if es_rojo(h.izq):
h = rotar_der(h)
if k == h.k and h.der is None:
return None
if not es_rojo(h.der) and not es_rojo(h.der.izq):
h = _mover_rojo_der(h)
if k == h.k:
h.k = _minimo(h.der).k # se sustituye por el sucesor
h.der = _borrar_min(h.der)
else:
h.der = _borrar(h.der, k)
return equilibrar(h)
class ArbolRN:
"""Rojinegro inclinado a la izquierda (Sedgewick): equivale a un árbol 2-3."""
def __init__(self):
self.raiz = None
def __len__(self):
return tam(self.raiz)
def __contains__(self, k):
h = self.raiz
while h is not None:
if k < h.k: h = h.izq
elif k > h.k: h = h.der
else: return True
return False
def insertar(self, k):
self.raiz = _insertar(self.raiz, k)
self.raiz.rojo = NEGRO
def borrar(self, k):
if k not in self:
return False
if not es_rojo(self.raiz.izq) and not es_rojo(self.raiz.der):
self.raiz.rojo = ROJO
self.raiz = _borrar(self.raiz, k)
if self.raiz is not None:
self.raiz.rojo = NEGRO
return True
def rank(self, k):
"""Número de claves estrictamente menores que k."""
h, r = self.raiz, 0
while h is not None:
if k <= h.k:
h = h.izq
else:
r += 1 + tam(h.izq)
h = h.der
return r
def select(self, i):
"""La clave de posición i (0 es la menor)."""
h = self.raiz
while h is not None:
t = tam(h.izq)
if i < t: h = h.izq
elif i > t: i, h = i - t - 1, h.der
else: return h.k
raise IndexError(i)
def rango(self, a, b):
"""Claves en [a, b] y número de nodos visitados."""
out, visitados = [], 0
def rec(h):
nonlocal visitados
if h is None:
return
visitados += 1
if a < h.k: rec(h.izq)
if a <= h.k <= b: out.append(h.k)
if h.k < b: rec(h.der)
rec(self.raiz)
return out, visitados
def altura(self):
def rec(h): return -1 if h is None else 1 + max(rec(h.izq), rec(h.der))
return rec(self.raiz)
def verificar(self):
"""Orden, tamaños, raíz negra, sin enlaces rojos a la derecha ni dos rojos seguidos, y altura negra uniforme."""
assert not es_rojo(self.raiz), "la raíz es roja"
def rec(h, lo, hi):
if h is None:
return 0
assert lo < h.k < hi, "orden roto"
assert not es_rojo(h.der), "enlace rojo a la derecha"
assert not (h.rojo and es_rojo(h.izq)), "dos rojos seguidos"
assert h.n == 1 + tam(h.izq) + tam(h.der), "tamaño desactualizado"
a, b = rec(h.izq, lo, h.k), rec(h.der, h.k, hi)
assert a == b, "altura negra desigual"
return a + (0 if h.rojo else 1)
rec(self.raiz, -math.inf, math.inf)
# --- prueba aleatoria contra una lista ordenada ---
rnd = random.Random(1)
A, ref = ArbolRN(), []
for paso in range(6000):
k = rnd.randrange(400)
i = bisect.bisect_left(ref, k)
esta = i < len(ref) and ref[i] == k
if rnd.random() < 0.55:
A.insertar(k)
if not esta: ref.insert(i, k)
else:
assert A.borrar(k) == esta
if esta: ref.pop(i)
if A.raiz is not None and (paso < 1500 or paso % 100 == 0):
A.verificar() # tras CADA operación al principio, después de vez en cuando
assert len(A) == len(ref)
assert [A.select(i) for i in range(len(ref))] == ref
visitas = []
for _ in range(300):
a = rnd.randrange(-10, 410)
b = a + rnd.randrange(0, 80)
out, v = A.rango(a, b)
assert out == [x for x in ref if a <= x <= b] and A.rank(a) == bisect.bisect_left(ref, a)
visitas.append((v, len(out), A.altura()))
print("6000 operaciones aleatorias verificadas;", len(ref), "claves; altura", A.altura())
print("rango [a, b]: máximo de visitados - k =", max(v - k for v, k, _ in visitas), " frente a 2(h+1) =", 2 * (visitas[0][2] + 1))
# --- altura frente a 2 log2 n ---
print("\n n altura (orden) altura (aleatorio) log2 n 2 log2(n+1) - 1")
for n in (2**10, 2**12, 2**14):
alturas = {}
for orden in ("ascendente", "aleatorio"):
B = ArbolRN()
claves = list(range(n))
if orden == "aleatorio":
rnd.shuffle(claves)
for k in claves:
B.insertar(k)
B.verificar()
alturas[orden] = B.altura()
print(f"{n:7d} {alturas['ascendente']:12d} {alturas['aleatorio']:16d} {math.log2(n):6.1f} {2 * math.log2(n + 1) - 1:10.1f}")The output gives two observations. After 6000 verified random operations, the tree still satisfies all invariants and range queries visit at most about nodes, within bound . Heights are well below : ascending keys give exactly (10, 12 and 14 for ), the best possible for a nearly perfect tree; random keys give 13, 15 and 19. Bound is a worst case that exists but is not typical.
AVL or red–black
Both are for everything; constants differ. AVL trees are better balanced (bound versus ) and search somewhat faster; red–black trees restructure less, with at most 2 rotations per insertion and 3 per deletion. General-purpose libraries thus often choose red–black: libstdc++ std::map, Java TreeMap and the Linux kernel’s generic tree use them. AVL is preferred when reads greatly outnumber writes. An interesting use: Java 8 turns HashMap buckets with many collisions into red–black trees, making hash flooding cost per operation instead of , provided keys implement Comparable (otherwise the tree cannot order equal-hash keys and scans them).
The external-memory model
So far we counted comparisons and visited nodes. That is appropriate only if all memory accesses cost the same, which they do not. Memory is a hierarchy: registers, caches, RAM, SSD, disk, network. Each level is much larger and slower than the previous one, and above all transfers blocks, not individual bytes: a cache line (64 bytes), page (4 KiB), disk sector. Once block-fetch latency is paid, the rest of its data arrives almost free. A perfect binary tree of keys has about 30 levels; if each node occupies a different block, disk search costs 30 random reads. The same disk may read hundreds of megabytes per second sequentially, but every random access pays full latency. Changing the cost model changes the best structure.
Literature often writes and to count blocks; here remains the number of tree keys and ratios are explicit.
Three basic bounds set the scale. Scanning contiguous elements costs I/Os, gaining factor . Searching an ordered set of keys costs and is optimal:
Proof
This is the same outcome-counting argument as the comparison sorting lower bound. Consider values distinct from every key: the answer is one of ordered gaps, and all answers are possible. Algorithm behavior (which block to request next, final answer) depends only on comparisons with transferred keys. Each transfer brings at most new keys, and the position of among them has only possible values; comparisons with seen keys add no information. Thus the decision tree branches at most ways per transfer and after transfers distinguishes at most cases. Distinguishing answers requires , that is .
∎Sorting costs : the Aggarwal–Vitter theorem. The upper bound is external merge sort: form sorted runs in memory (one read/write pass) and merge up to at a time, with one input page per run and one output page. Each merge pass divides the number of runs by , so passes are needed, each reading and writing all blocks. The lower bound follows a similar information count. There are possible input orders, so bits must be learned. A read places the block elements among those already in fast memory, contributing at most bits. Also, the first read of each of the input blocks can reveal internal order of its elements, bits, at most total. Around bits remain, arriving at only per read, giving reads (the full argument including writes is subtler). Since is usually 1 or 2, sorting elements in practice costs a few times reading them.
A processor cache follows the same model, with cache size and line size. Use it as a guide rather than a magic formula: how many distinct blocks does my algorithm touch?
B-trees
The model’s conclusion is immediate: if a node occupies one block, put as many keys in it as fit. A degree- tree has height instead of : with 4 KiB blocks and 16-byte entries, and each node replaces eight binary levels. This was Bayer and McCreight’s idea (1972), when disks were already the bottleneck.
gives the preceding 2–3–4 tree: a red–black tree is a minimum-degree-2 B-tree encoded in binary. In external memory choose as large as allows a full node to fit in a block.
Proof
The minimum number of nodes per level is 1 (root), 2 (root has at least 2 children), , , up to at level , because each non-root internal node has at least children. Since each node except the root has at least keys and the root at least 1,
and solving gives .
∎A search descends from root to leaf, choosing a child at each node by binary search among its keys (within the block, free in the model). It costs transfers.
Insertion descends to the target leaf. The rule is never to return upward: split on descent each full node ( keys) into two with keys, promoting the median to the parent, which was just checked and is not full. If the root is full, split it first and the tree grows upward: the only way height changes, so leaves always remain at the same depth. Deletion reverses this: before descending into a child with only keys, lend it a sibling key by rotating through the parent, or merge it with a sibling by moving down their separator. If the root becomes empty, the tree shrinks at the top.
Proof
Without deletions node count never falls, and each split raises it: by one for a non-root node (new sibling), by two for the root (new sibling and root). Starting with one node, splits are at most final node count minus 1. Finally the root has at least one key and each other node at least , so with nodes and keys, . Thus splits are at most .
∎Two practical consequences. Nodes in a large B-tree built with random insertions fill, on average, only of capacity (Yao, 1978); the next cell measures 63–69% with . Most insertions modify only one leaf: tree height rarely increases.
B-trees. Databases and file systems almost always use a variant: all keys and data live in leaves; internal nodes store separators only, so more fit per block (higher degree); and leaves are linked in a list. A range query costs one search of plus a leaf scan, . With 4 KiB blocks and 16-byte entries ( per node, about 255 keys per leaf), an index with keys has about 3.9 million leaves, 15,300 nodes above, about 60 on the next level and one root: four levels. The top three occupy about 60 MiB and fit in RAM on any machine, so a search needs one disk read.
Two observations from the interactive deserve emphasis. First, height falls to but comparisons do not: a B-tree makes about comparisons total (binary search in each node costs across nodes), as many as a binary tree. It saves blocks, not comparisons, so a comparison-counting model does not distinguish them. Second, cannot grow without limit: if a node exceeds a block, each visit costs multiple transfers; if latency is small relative to reading one key, fetching many is not worthwhile. The minimum of occurs at approximately satisfying , where is access latency measured in transferred keys: it grows somewhat slower than .
The same logic explains a surprising fact: even in RAM, B-trees outperform binary trees. The unit is now a cache line rather than disk. Thus Rust’s BTreeMap uses nodes of up to 11 keys, and C++ Abseil offers btree_map as an alternative to std::map: more comparisons per node, but adjacent in memory.
import math, random, bisect, heapq
class NodoB:
__slots__ = ("claves", "hijos")
def __init__(self, claves=None, hijos=None):
self.claves = claves if claves is not None else []
self.hijos = hijos if hijos is not None else [] # vacío si es hoja
class ArbolB:
"""B-tree de grado mínimo t: cada nodo tiene entre t-1 y 2t-1 claves (la raíz, entre 1 y 2t-1)."""
def __init__(self, t):
assert t >= 2
self.t = t
self.raiz = NodoB()
self.visitas = 0 # nodos leídos: cada uno es una transferencia de bloque
def buscar(self, k):
x = self.raiz
while True:
self.visitas += 1
i = bisect.bisect_left(x.claves, k)
if i < len(x.claves) and x.claves[i] == k:
return True
if not x.hijos:
return False
x = x.hijos[i]
def _dividir(self, x, i):
"""Parte el hijo lleno x.hijos[i] en dos nodos de t-1 claves y sube la mediana a x."""
t, y = self.t, x.hijos[i]
z = NodoB(y.claves[t:], y.hijos[t:])
mediana = y.claves[t - 1]
y.claves, y.hijos = y.claves[:t - 1], y.hijos[:t]
x.claves.insert(i, mediana)
x.hijos.insert(i + 1, z)
def insertar(self, k):
r = self.raiz
if len(r.claves) == 2 * self.t - 1: # raíz llena: el árbol crece por arriba
self.raiz = NodoB([], [r])
self._dividir(self.raiz, 0)
x = self.raiz
while True:
i = bisect.bisect_left(x.claves, k)
if i < len(x.claves) and x.claves[i] == k:
return False
if not x.hijos:
x.claves.insert(i, k)
return True
if len(x.hijos[i].claves) == 2 * self.t - 1: # se divide al bajar para no volver a subir
self._dividir(x, i)
if k == x.claves[i]:
return False
if k > x.claves[i]:
i += 1
x = x.hijos[i]
def borrar(self, k):
"""Borrado de arriba abajo: antes de bajar a un hijo con solo t-1 claves se le presta una o se fusiona."""
t = self.t
def asegurar(x, i):
"""Garantiza que x.hijos[i] tenga al menos t claves; devuelve el índice donde seguir."""
h = x.hijos[i]
if len(h.claves) >= t:
return i
izq = x.hijos[i - 1] if i > 0 else None
der = x.hijos[i + 1] if i + 1 < len(x.hijos) else None
if izq is not None and len(izq.claves) >= t: # préstamo del hermano izquierdo, rotando por el padre
h.claves.insert(0, x.claves[i - 1])
x.claves[i - 1] = izq.claves.pop()
if izq.hijos:
h.hijos.insert(0, izq.hijos.pop())
return i
if der is not None and len(der.claves) >= t: # préstamo del derecho
h.claves.append(x.claves[i])
x.claves[i] = der.claves.pop(0)
if der.hijos:
h.hijos.append(der.hijos.pop(0))
return i
j = i if der is not None else i - 1 # fusión con un hermano: baja el separador
a, b = x.hijos[j], x.hijos[j + 1]
a.claves += [x.claves.pop(j)] + b.claves
a.hijos += b.hijos
x.hijos.pop(j + 1)
return j
x = self.raiz
while True:
i = bisect.bisect_left(x.claves, k)
esta = i < len(x.claves) and x.claves[i] == k
if not x.hijos:
if esta:
x.claves.pop(i)
break
if esta:
if len(x.hijos[i].claves) >= t: # se sustituye por el predecesor y se borra abajo
p = x.hijos[i]
while p.hijos:
p = p.hijos[-1]
x.claves[i] = k = p.claves[-1]
x = x.hijos[i]
continue
if len(x.hijos[i + 1].claves) >= t: # o por el sucesor
p = x.hijos[i + 1]
while p.hijos:
p = p.hijos[0]
x.claves[i] = k = p.claves[0]
x = x.hijos[i + 1]
continue
a, b = x.hijos[i], x.hijos[i + 1] # ambos hijos mínimos: se fusionan con k en medio
a.claves += [x.claves.pop(i)] + b.claves
a.hijos += b.hijos
x.hijos.pop(i + 1)
x = a
continue
x = x.hijos[asegurar(x, i)]
if not self.raiz.claves and self.raiz.hijos: # la raíz se vació: el árbol decrece por arriba
self.raiz = self.raiz.hijos[0]
def altura(self):
h, x = 0, self.raiz
while x.hijos:
x, h = x.hijos[0], h + 1
return h
def nodos(self):
pila, c = [self.raiz], 0
while pila:
x = pila.pop()
c += 1
pila += x.hijos
return c
def claves_en_orden(self):
out = []
def rec(x):
for i, c in enumerate(x.claves):
if x.hijos:
rec(x.hijos[i])
out.append(c)
if x.hijos:
rec(x.hijos[-1])
rec(self.raiz)
return out
def verificar(self):
t, prof = self.t, set()
def rec(x, d, lo, hi, es_raiz):
assert len(x.claves) <= 2 * t - 1, "nodo desbordado"
assert es_raiz or len(x.claves) >= t - 1, "nodo con pocas claves"
assert x.claves == sorted(x.claves) and all(lo < c < hi for c in x.claves), "orden roto"
if not x.hijos:
prof.add(d)
return
assert len(x.hijos) == len(x.claves) + 1, "hijos != claves + 1"
cotas = [lo] + x.claves + [hi]
for i, h in enumerate(x.hijos):
rec(h, d + 1, cotas[i], cotas[i + 1], False)
rec(self.raiz, 0, -math.inf, math.inf, True)
assert len(prof) == 1, "las hojas no están a la misma profundidad"
# --- prueba aleatoria: t = 2 es el árbol 2-3-4 ---
rnd = random.Random(2)
for t in (2, 3, 8):
A, ref = ArbolB(t), set()
for paso in range(4000):
k = rnd.randrange(600)
if rnd.random() < 0.55:
assert A.insertar(k) == (k not in ref)
ref.add(k)
else:
A.borrar(k)
ref.discard(k)
if paso % 7 == 0:
A.verificar()
assert A.claves_en_orden() == sorted(ref)
print(f"t = {t}: 4000 operaciones verificadas, {len(ref)} claves, altura {A.altura()}")
# --- bloques por búsqueda: rojinegro (de la celda anterior) frente a B-trees ---
n = 20000
claves = list(range(n))
rnd.shuffle(claves)
rn = ArbolRN()
for k in claves:
rn.insertar(k)
def profundidad(h, k):
c = 0
while h is not None:
c += 1
if k < h.k: h = h.izq
elif k > h.k: h = h.der
else: break
return c
consultas = [rnd.randrange(n) for _ in range(2000)]
visitas_rn = sum(profundidad(rn.raiz, k) for k in consultas) / len(consultas)
print(f"\nn = {n}. Rojinegro: {visitas_rn:.2f} nodos por búsqueda (altura {rn.altura()}).")
print(" t claves por nodo nodos por búsqueda altura llenado cota h <= log_t((n+1)/2)")
for t in (4, 16, 64, 128):
b = ArbolB(t)
for k in claves:
b.insertar(k)
b.verificar()
b.visitas = 0
for k in consultas:
b.buscar(k)
llenado = n / (b.nodos() * (2 * t - 1))
assert b.altura() <= math.log((n + 1) / 2, t)
print(f"{t:4d} {t - 1:3d} a {2 * t - 1:3d} {b.visitas / len(consultas):8.2f} {b.altura():5d} {llenado:6.2f} {math.log((n + 1) / 2, t):8.2f}")
# --- ordenar en memoria externa: mezcla de varias vías, contando bloques ---
def mergesort_externo(datos, M, B):
"""Cuenta bloques leídos y escritos. M y B en elementos; se mezclan M//B - 1 runs a la vez."""
transferencias = 0
runs = []
for i in range(0, len(datos), M): # formación de runs: se lee y se escribe cada bloque una vez
run = sorted(datos[i:i + M])
runs.append(run)
transferencias += 2 * math.ceil(len(run) / B)
k = max(2, M // B - 1) # una página de entrada por run y una de salida
pasadas = 1
while len(runs) > 1:
nuevos = []
for g in range(0, len(runs), k):
grupo = runs[g:g + k]
fusion = list(heapq.merge(*grupo))
nuevos.append(fusion)
transferencias += sum(math.ceil(len(r) / B) for r in grupo) + math.ceil(len(fusion) / B)
runs = nuevos
pasadas += 1
return runs[0], transferencias, pasadas
N = 20000
datos = [rnd.randrange(10**6) for _ in range(N)]
print("\nmezcla externa de N = 20000 elementos:")
print(" M B runs fan-in pasadas transferencias fórmula 2(N/B)(1 + ceil(log_k(N/M)))")
for M, B in ((500, 10), (500, 100), (200, 100)):
res, tr, pas = mergesort_externo(datos, M, B)
assert res == sorted(datos)
k = max(2, M // B - 1)
runs = math.ceil(N / M)
pred = 2 * math.ceil(N / B) * (1 + math.ceil(math.log(runs, k) - 1e-12))
print(f"{M:5d} {B:5d} {runs:5d} {k:6d} {pas:8d} {tr:14d} {pred:14d}")External merging plays the role of merge in merge sort, but with a fundamental difference: it merges many runs at once instead of two. Pairwise external merging would be correct but cost full passes; wide merging costs , usually one or two. This is the B-tree story again: exploit block transfers whose fixed latency dominates.
Cache-oblivious: the parameter-free version
B-trees have a philosophical limitation: they need to know . Real hierarchies have many at once (cache line, virtual-memory page, disk block), differing across machines. Frigo, Leiserson, Prokop and Ramachandran (1999) proposed algorithms that mention neither nor yet are optimal for all of them.
This suffices for the whole hierarchy. An algorithm optimal for any and is optimal for each pair of consecutive levels, and an LRU cache of twice the size makes at most twice as many misses as optimal (Sleator and Tarjan, 1985), justifying the optimal-replacement assumption. Examples include scanning an array, transposing or multiplying matrices by recursive blocking (halve until the subproblem fits in cache, without knowing when), funnelsort, which reaches the Aggarwal–Vitter cost under the tall-cache assumption , and our topic: tree search.
The idea is a memory layout, not a new algorithm. Search in a perfect binary tree is unchanged; what changes is each node’s array location. Heap level order fails: initial levels fit together, but once a node and child are more than apart, each step reaches a new block. In-order layout fails too. The van Emde Boas layout halves a tree of levels: store the top tree first ( levels), followed by each bottom subtree in sequence, recursively applying the same rule to every piece.
Proof
Measure pieces by levels: a piece of levels has nodes, and recursion splits it into a top piece of levels and bottom pieces of . Fix and let be the largest integer with , so . Stop recursion once a piece has at most levels (at most nodes): these terminal pieces are basic. Each recursive piece occupies a contiguous array range, so a basic piece touches at most two blocks. Count basic pieces crossed by a path.
Let be that number for a piece of levels. If , ; otherwise the path crosses the top and one bottom piece, and . Inductively for every . If both halves have at most levels, because . If both exceed , sum the induction hypotheses: . If only the bottom exceeds , then and , giving and , equivalent to .
With nodes, the tree has levels. If , then , the path lies within one basic piece and touches at most blocks. If , it crosses at most basic pieces and touches at most twice as many blocks: .
∎The constant 4 is pessimistic (in the interactive’s 12-level tree, average van Emde Boas layout cost is 1.3–1.5 times lower bound ), but the bound’s form matters: for all with the same array. B-trees remain practically useful and also support insertion; dynamic cache-oblivious B-trees exist (Bender, Demaine and Farach-Colton, 2000) but are considerably more complex. Cache-oblivious design remains useful as a principle: recurse until pieces fit instead of fixed-size blocks. Fast/slow memory reasoning reappears in FlashAttention I/O analysis in module 18; the physical hierarchy abstracted by the model (cache lines, pages, prefetching) is covered in module 9, and module 11’s k-d and ball trees extend search trees to multiple dimensions.
In libraries
Python’s standard library includes no search tree. It has a sorted list with bisect, seemingly naive but highly competitive: list insertion costs but is a contiguous memmove, very fast up to large sizes, and search is binary over contiguous memory.
import bisect, random, time
import numpy as np
n = 20000
rnd = random.Random(1)
claves = [rnd.randrange(10**9) for _ in range(n)]
t0 = time.perf_counter()
lista = []
for k in claves:
bisect.insort(lista, k)
t_lista = time.perf_counter() - t0
t0 = time.perf_counter()
A = ArbolRN()
for k in claves:
A.insertar(k)
t_arbol = time.perf_counter() - t0
print(f"{n} inserciones aleatorias: lista con bisect {t_lista*1e3:.0f} ms, rojinegro en Python {t_arbol*1e3:.0f} ms")
# las mismas consultas de rank y de rango con las dos estructuras
a, b = lista[5000], lista[5100]
assert bisect.bisect_left(lista, a) == A.rank(a) == 5000
i, j = bisect.bisect_left(lista, a), bisect.bisect_right(lista, b)
rango_lista = lista[i:j]
rango_arbol, visitados = A.rango(a, b)
assert rango_lista == rango_arbol
print("rango de", len(rango_lista), "claves:", visitados, "nodos visitados en el árbol; con la lista, 2 búsquedas binarias y un corte")
# consultas en lote con NumPy: searchsorted hace una búsqueda binaria por elemento, en C
arr = np.array(lista)
q = np.array([rnd.randrange(10**9) for _ in range(100000)])
t0 = time.perf_counter()
pos = np.searchsorted(arr, q)
t_np = time.perf_counter() - t0
print(f"100000 rank con np.searchsorted: {t_np*1e3:.0f} ms")
assert all(int(pos[x]) == bisect.bisect_left(lista, int(q[x])) for x in range(0, 100000, 997))Timing depends on the machine and, here, the Pyodide environment, but the pattern is stable: with tens of thousands of keys, a sorted list beats a pure Python tree, because the tree pays interpreter overhead at each node and the list pays only for a C-level shift. Beyond some size, linear insertion cost dominates; an intermediate solution is sortedcontainers.SortedList (Grant Jenks): a list of small lists, a two-level B-tree, whose documentation claims it beats tree implementations through memory locality.
# No se ejecuta aquí (no está en el entorno del navegador); API de la biblioteca sortedcontainers
from sortedcontainers import SortedList
sl = SortedList([5, 1, 9])
sl.add(7) # O(log n) amortizado, con memmove en listas de ~1000 elementos
sl.irange(2, 8) # rango [2, 8]: iterador perezoso
sl.bisect_left(7) # rank
sl[2] # select
sl.discard(1)
A quick selection guide:
| Need | Use | Why |
|---|---|---|
| Membership only, no ordering | hash table | expected and faster than any tree |
| Ordered map in RAM, many writes | red–black (std::map, TreeMap) or in-memory B-tree | guaranteed; B-trees win through cache locality |
| Ordered map in RAM, many reads | AVL or sorted list with bisect | lower height; the list is unbeatable if it rarely changes |
| Disk data, range queries | B-tree | blocks and linked leaves make the range almost free |
| Next most urgent, no full order | heap | do not pay to maintain unused ordering |
Real use confirms the pattern. Databases and file systems use B-trees or B-trees (PostgreSQL, SQLite and InnoDB indexes, ext4 indexed directories with a shallow tree over name hashes, btrfs copy-on-write trees). Languages with in-memory ordered maps use red–black trees (libstdc++ std::map, Java TreeMap) or increasingly B-trees with small nodes (Rust BTreeMap).
Common mistakes
Exercises
Step 1 of 4. What does a minimum-node AVL of height look like, and what recurrence does satisfy?
Step 1 of 4. What is first proved about subtree size?
rango(raiz, a, b), returning in increasing order all BST keys with . Nodes have fields k, izq and der. Do not traverse branches that cannot contain keys in the interval: tests count reads of nodo.k and require at most reads, where is output size and height. Read nodo.k only once per visited node (save it in a local variable).def rango(raiz, a, b):
"""Claves k con a <= k <= b, en orden creciente. Visita O(h + k) nodos."""
resultado = []
# tu código: recorrido simétrico podando las ramas que no pueden contener claves del intervalo
return resultadoSummary
- A BST supports search, insertion, deletion, successor and range in . Random insertions give average depth , but sorted keys turn it into a list: height must be guaranteed.
- A rotation changes shape with three pointers without changing in-order traversal. It is the only movement AVL and red–black trees need, with metadata updated bottom-up.
- AVL maintains and has height (the thinnest are Fibonacci trees); insertion needs at most one repair (single or double rotation), deletion up to .
- A red–black tree encodes a 2–3–4 tree in binary: recoloring = overflowing-node split, rotation = node rearrangement. Height is , with at most 2 rotations per insertion and 3 per deletion. The left-leaning variant is a 2–3 tree implemented in one page, at the cost of losing the rotation bound.
- In external memory only transferred blocks count: search costs , scan and sort . A B-tree of minimum degree has height , with the same comparisons as a binary tree but far fewer blocks.
- A cache-oblivious algorithm achieves those costs without knowing or . The van Emde Boas layout stores a perfect tree in an array so any search touches blocks for all simultaneously.