Module contents
Lesson 8 of 33Core 115 min

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, Java TreeMap or Rust BTreeMap: iterate keys in order, ask for the greatest key below xx (predecessor) or smallest above xx (successor), or extract all in a range.
  • Database indexes. WHERE fecha BETWEEN a AND b or ORDER BY without 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 tt,” 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:

StructureSearchInsertMinimumSuccessorRange with kk results
Hash tableO(1)\bigO(1) expectedO(1)\bigO(1) amortizedO(n)\bigO(n)O(n)\bigO(n)O(n)\bigO(n)
Sorted arrayO(log⁡n)\bigO(\log n)O(n)\bigO(n)O(1)\bigO(1)O(log⁡n)\bigO(\log n)O(log⁡n+k)\bigO(\log n + k)
Binary heapO(n)\bigO(n)O(log⁡n)\bigO(\log n)O(1)\bigO(1)O(n)\bigO(n)O(n)\bigO(n)
Balanced search treeO(log⁡n)\bigO(\log n)O(log⁡n)\bigO(\log n)O(log⁡n)\bigO(\log n)O(log⁡n)\bigO(\log n)O(log⁡n+k)\bigO(\log n + k)

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 O(h)\bigO(h) in the first lesson’s asymptotic notation:

  • Search kk. Compare with the root: if smaller, go left; if larger, right. Reaching an empty child means kk is absent.
  • Minimum and maximum. Always descend left (or right).
  • Successor of kk. It is the minimum of the right subtree if present; otherwise the lowest ancestor from which kk descends left. Find it by descending from the root and remembering the last left turn.
  • Insert kk. Search for kk and attach a new node at the empty child: it always enters as a leaf.
  • Delete kk. 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 [a,b][a, b]. Perform pruned in-order traversal: do not descend left of a node with key ≤a\le a or right of one with key ≥b\ge b. Every visited node is either inside the interval (at most kk) or on one of the search paths for aa and bb (at most 2(h+1)2(h+1)), yielding cost O(h+k)\bigO(h + k).
  • Rank and selection. If every node stores subtree size, count keys smaller than kk by adding 1+1 + left-subtree size whenever descending right (and, upon finding kk, its left-subtree size); find the key of rank ii by comparing ii with that size. Both take O(h)\bigO(h).
[ ]Binary search tree from scratchBrowser
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 i∈{1,…,n}i \in \{1, \dots, n\} among the keys is uniform. This leaves i−1i - 1 keys on the left and n−in - i on the right, each side a random BST of its size. Since each of the remaining n−1n - 1 nodes is one level deeper than in its own subtree,

P(n)=(n−1)+1n∑i=1n(P(i−1)+P(n−i))=(n−1)+2n∑i=0n−1P(i),P(0)=0.P(n) = (n - 1) + \frac{1}{n}\sum_{i=1}^{n}\big(P(i-1) + P(n-i)\big) = (n-1) + \frac{2}{n}\sum_{i=0}^{n-1}P(i), \qquad P(0) = 0.

This is the recurrence for expected quicksort comparisons. Solve it by subtracting the equation for n−1n - 1 from that for nn to eliminate the sum: nP(n)−(n−1)P(n−1)=2(n−1)+2P(n−1)nP(n) - (n-1)P(n-1) = 2(n-1) + 2P(n-1), that is, nP(n)=(n+1)P(n−1)+2(n−1)nP(n) = (n+1)P(n-1) + 2(n-1). Dividing by n(n+1)n(n+1) gives P(n)n+1=P(n−1)n+2(n−1)n(n+1)\frac{P(n)}{n+1} = \frac{P(n-1)}{n} + \frac{2(n-1)}{n(n+1)} and, since 2(n−1)n(n+1)=4n+1−2n\frac{2(n-1)}{n(n+1)} = \frac{4}{n+1} - \frac{2}{n}, it telescopes:

P(n)n+1=∑j=1n(4j+1−2j)=4(Hn+1−1)−2Hn=2Hn−4+4n+1,\frac{P(n)}{n+1} = \sum_{j=1}^{n}\Big(\frac{4}{j+1} - \frac{2}{j}\Big) = 4(H_{n+1} - 1) - 2H_n = 2H_n - 4 + \frac{4}{n+1},

whence P(n)=2(n+1)Hn−4nP(n) = 2(n+1)H_n - 4n. Since Hn=ln⁡n+γ+o(1)H_n = \ln n + \gamma + o(1), the average is ∼2ln⁡n\sim 2\ln n.

∎

A typical node is therefore 39% deeper than in a perfect tree (2ln⁡n=1.386log⁡2n2\ln n = 1.386\log_2 n). The worst node is another story: expected height grows as αln⁡n\alpha\ln n with α≈4.311\alpha \approx 4.311 (Devroye, 1986; Reed, 2003 refines lower-order terms), about three log⁡2n\log_2 n for large nn. Still, it is logarithmic. The preceding cell measures 40 trees with n=1000n = 1000: 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: Cn=1n+1(2nn)C_n = \frac{1}{n+1}\binom{2n}{n} different BSTs have the same nn keys, and all are valid. Balancing moves between them with a cheap operation: rotation.

The check takes one line: in y(x(A,B),C)y(x(A,B),C) read A x B y CA\,x\,B\,y\,C and in x(A,y(B,C))x(A,y(B,C)) 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.

InteractiveRotations at your fingertips
1234567891011In-order traversal (never changes)1234567891011
  • node that just rose
  • subtree that changes parent
  • balance factor outside {−1,0,1}\{-1, 0, 1\}
Click a node to rotate its edge with its parent: the node rises and the parent moves down to the opposite side. Notice that no node moves horizontally.
Starting tree
11
Height hh (edges)10
Minimum possible height3
Rotations performed0
Day, Stout, Warren from the initial tree8 rotations
AVL inserting 1..n in order7 rotations
Nodes violating AVL balance9
In-order traversalintact
Start with 11 keys inserted in order: a chain of height 10. Click any node to rotate its edge with its parent (it rises and the parent descends). Nodes move only vertically because their column is their in-order position, shown below and never changed. The orange subtree alone changes parent. Try reducing height to its minimum (3) with the fewest rotations and compare with the Equilibrar button, which applies the Day–Stout–Warren sequence, and the AVL reading. Enable balance factors and see which spike in the chain and random tree. Starting from the perfect tree, how many rotations break it? How many repair it?

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 1,…,111, \dots, 11 in order into an AVL costs 7 total, spread along the way. A later cell checks the general pattern: inserting 1,…,n1, \dots, n in order into an AVL takes exactly n−⌈log⁡2(n+1)⌉n - \lceil\log_2(n+1)\rceil rotations at every tested size, nearly one per key. Rotations are not free, but they are local: AVL and red–black trees need O(log⁡n)\bigO(\log n) or fewer per update.

AVL trees

This local condition forces logarithmic height. To see why, ask what the thinnest AVL of a given height hh 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 h−1h-1 and another of height h−2h-2 (balance allows the second to be one lower, no more), so N(h)=1+N(h−1)+N(h−2)N(h) = 1 + N(h-1) + N(h-2), the Fibonacci linear recurrence shifted by one. Its solution grows as φh\varphi^h, and solving for hh gives the bound. Initial values are N(0),…,N(10)=1,2,4,7,12,20,33,54,88,143,232N(0), \dots, N(10) = 1, 2, 4, 7, 12, 20, 33, 54, 88, 143, 232.

The table compares longest-path node counts for a perfect tree with nn keys, worst AVL height (largest h+1h + 1 with N(h)≤nN(h) \le n), and worst red–black height (the same calculation on its thinnest trees), alongside the bound 2log⁡2(n+1)2\log_2(n+1) proved for the latter in the next section:

nnPerfectAVL worst caseRed–black worst caseBound 2log⁡2(n+1)2\log_2(n+1)
10310^310141719
10610^620283739
10910^930425759

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 ±2\pm 2 (call it zz) according to where the node landed:

  • Outer case (heavy child yy of zz is heavy on the same side: left–left or right–right). One rotation on zz 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 yy with its child to turn it into an outer case, then zz.

Why does this work, and why is one repair enough? Let hh be the height of CC in the left–left case, z(y(A,B),C)z(y(A, B), C). Before insertion zz was balanced, so yy had height at most h+1h+1. Inserting in AA grew yy to h+2h+2, so now alt⁡(A)=h+1\operatorname{alt}(A) = h+1; since the prior height of yy was h+1h+1, alt⁡(B)≤h\operatorname{alt}(B) \le h, and since yy remains balanced, alt⁡(B)=h\operatorname{alt}(B) = h. After rotating right, y(A,z(B,C))y(A, z(B, C)): zz has two children of height hh, so height h+1h+1, and yy has two children of height h+1h+1, so height h+2h+2. That is exactly the height zz had before insertion (1+max⁡(h+1,h)1 + \max(h+1, h)), 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 Θ(log⁡n)\Theta(\log n) rotations per deletion, one per level, in the worst case. Each rotation is O(1)\bigO(1), so total operation cost remains O(log⁡n)\bigO(\log n), but Θ(log⁡n)\Theta(\log n) rotations lead many libraries to prefer red–black trees.

[ ]AVL: rotations and Fibonacci treesBrowser
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 1.44log⁡2n1.44\log_2 n to 2log⁡2n2\log_2 n 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 bb black nodes, so at least bb nodes, and since every red node is directly below a black one (root is black and no two reds are adjacent), at most 2b2b.

The classical proof, guided in the exercises, has two steps: a node’s subtree of black height bb contains at least 2b−12^b - 1 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 bb and at least 2b−12^b - 1 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.

InteractiveRed–black and 2–3–4 together
Red-black tree (binary)10515371218The same tree as a 2-3-4 tree10357121518
  • black node
  • red node
  • 2-3-4 node (black with red children)
  • touched in this step
  • overflowing (4 keys)
Red-black. Red-black tree with 7 keys. Insert a key and watch the steps: each can be read as both a red-black rule and an operation on a 2-3-4 node. Key 1 triggers recoloring.
2-3-4. The 2-3-4 tree below has all leaves at the same depth, guaranteeing logarithmic height.
Keys to insert
1
Keys nn7
Red-black height (edges)2
Bound 2log⁡2(n+1)−12\log_2(n+1) - 15.0
2-3-4 levels2
Black height2
Splits (recolorings)0
Rotations0
Red-black rulessatisfied
Above, the red–black tree; green capsules group each black node with its red children. Below, the same tree as a 2–3–4 tree: each capsule is a multiway node. Start with key 1, which lands under a red parent with red uncle: recoloring in the red–black tree; in the 2–3–4 tree a three-key node overflows with the fourth and splits, promoting a key. Then insert 2: it lands as an inner child of a red parent with black (empty) uncle and is fixed with two rotations; in the 2–3–4 tree the same three keys change shape without changing the tree. Ascending keys show the outer case needing one rotation. With «Vaciar el árbol» and ascending keys, compare rotations with splits and see how all 2–3–4 leaves stay at the same depth. Readouts compare black height with 2–3–4 levels.

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:

UncleRed–black2–3–4 treeWhat happens next
(parent is black)no violationkey enters a node with fewer than 3 keysnothing
redparent and uncle become black, grandparent rednode already had 3 keys; a fourth overflows it, so split in two and promote the middle keygrandparent may have a red parent: repeat two levels up
blackone or two rotations and a color swapthree keys change binary shapedone: 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 nn insertions is O(n)\bigO(n).

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 Θ(log⁡n)\Theta(\log n). 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 O(1)\bigO(1) rotation bound per update and may make Θ(log⁡n)\Theta(\log n); total cost remains O(log⁡n)\bigO(\log n). The verifier checks invariants after every operation and a randomized test compares with a sorted list.

[ ]Left-leaning red–black tree with invariant verifierBrowser
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 k+12k + 12 nodes, within bound k+2(h+1)k + 2(h+1). Heights are well below 2log⁡2(n+1)−12\log_2(n+1) - 1: ascending keys give exactly log⁡2n\log_2 n (10, 12 and 14 for n=210,212,214n = 2^{10}, 2^{12}, 2^{14}), the best possible for a nearly perfect tree; random keys give 13, 15 and 19. Bound 2log⁡2n2\log_2 n is a worst case that exists but is not typical.

AVL or red–black

Both are O(log⁡n)\bigO(\log n) for everything; constants differ. AVL trees are better balanced (bound 1.44log⁡2n1.44\log_2 n versus 2log⁡2n2\log_2 n) 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 O(log⁡n)\bigO(\log n) per operation instead of O(n)\bigO(n), 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 10910^9 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 n=N/Bn = N/B and m=M/Bm = M/B to count blocks; here nn remains the number of tree keys and ratios are explicit.

Three basic bounds set the scale. Scanning NN contiguous elements costs ⌈N/B⌉\lceil N/B \rceil I/Os, gaining factor BB. Searching an ordered set of NN keys costs Θ(log⁡BN)\Theta(\log_B N) and is optimal:

Proof

This is the same outcome-counting argument as the comparison sorting lower bound. Consider values xx distinct from every key: the answer is one of N+1N + 1 ordered gaps, and all N+1N + 1 answers are possible. Algorithm behavior (which block to request next, final answer) depends only on comparisons with transferred keys. Each transfer brings at most BB new keys, and the position of xx among them has only B+1B + 1 possible values; comparisons with seen keys add no information. Thus the decision tree branches at most B+1B + 1 ways per transfer and after tt transfers distinguishes at most (B+1)t(B+1)^t cases. Distinguishing N+1N + 1 answers requires (B+1)t≥N+1(B+1)^t \ge N + 1, that is t≥log⁡B+1(N+1)t \ge \log_{B+1}(N+1).

∎

Sorting costs Θ ⁣(NBlog⁡M/BNB)\Theta\!\big(\tfrac{N}{B}\log_{M/B}\tfrac{N}{B}\big): the Aggarwal–Vitter theorem. The upper bound is external merge sort: form N/MN/M sorted runs in memory (one read/write pass) and merge up to M/B−1M/B - 1 at a time, with one input page per run and one output page. Each merge pass divides the number of runs by M/B−1M/B - 1, so ⌈log⁡M/B−1(N/M)⌉\lceil \log_{M/B - 1}(N/M) \rceil passes are needed, each reading and writing all 2N/B2N/B blocks. The lower bound follows a similar information count. There are N!N! possible input orders, so log⁡2N!≈Nlog⁡2N\log_2 N! \approx N\log_2 N bits must be learned. A read places the BB block elements among those already in fast memory, contributing at most log⁡2(MB)≤Blog⁡2(eM/B)=O(Blog⁡(M/B))\log_2\binom{M}{B} \le B\log_2(eM/B) = \bigO(B\log(M/B)) bits. Also, the first read of each of the N/BN/B input blocks can reveal internal order of its BB elements, log⁡2B!≤Blog⁡2B\log_2 B! \le B\log_2 B bits, at most Nlog⁡2BN\log_2 B total. Around Nlog⁡2(N/B)N\log_2(N/B) bits remain, arriving at only O(Blog⁡(M/B))\bigO(B\log(M/B)) per read, giving Ω(NBlog⁡M/BNB)\Omega\big(\tfrac{N}{B}\log_{M/B}\tfrac{N}{B}\big) reads (the full argument including writes is subtler). Since log⁡M/B(N/B)\log_{M/B}(N/B) is usually 1 or 2, sorting NN elements in practice costs a few times reading them.

A processor cache follows the same model, with MM cache size and BB 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-BB tree has height log⁡BN\log_B N instead of log⁡2N\log_2 N: with 4 KiB blocks and 16-byte entries, B=256B = 256 and each node replaces eight binary levels. This was Bayer and McCreight’s idea (1972), when disks were already the bottleneck.

t=2t = 2 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 tt 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), 2t2t, 2t22t^2, up to 2th−12t^{h-1} at level hh, because each non-root internal node has at least tt children. Since each node except the root has at least t−1t - 1 keys and the root at least 1,

n  ≥  1+(t−1)∑i=1h2ti−1=1+2(th−1)=2th−1,n \;\ge\; 1 + (t-1)\sum_{i=1}^{h} 2t^{i-1} = 1 + 2(t^h - 1) = 2t^h - 1,

and solving gives th≤(n+1)/2t^h \le (n+1)/2.

∎

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 h+1=O(log⁡tn)h + 1 = \bigO(\log_t n) transfers.

Insertion descends to the target leaf. The rule is never to return upward: split on descent each full node (2t−12t - 1 keys) into two with t−1t - 1 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 t−1t - 1 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 t−1t - 1, so with ν\nu nodes and n′≤nn' \le n keys, n′≥1+(ν−1)(t−1)n' \ge 1 + (\nu - 1)(t - 1). Thus splits are at most ν−1≤(n′−1)/(t−1)≤(n−1)/(t−1)\nu - 1 \le (n' - 1)/(t - 1) \le (n - 1)/(t - 1).

∎

Two practical consequences. Nodes in a large B-tree built with random insertions fill, on average, only ln⁡2≈69 %\ln 2 \approx 69\,\% of capacity (Yao, 1978); the next cell measures 63–69% with n=20 000n = 20\,000. 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 [a,b][a, b] costs one search of aa plus a leaf scan, O(log⁡BN+k/B)\bigO(\log_B N + k/B). With 4 KiB blocks and 16-byte entries (B=256B = 256 per node, about 255 keys per leaf), an index with 10910^9 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.

InteractiveB-tree I/O counter
Block transfers per search (mean of 1500, with LRU cache)
BST with scattered nodes16.9BST in BFS (level) order10.2BST in van Emde Boas order2.74B-tree2.71
Dashed mark: theoretical cost without cache (log⁡2n\log_2 n, log⁡2(n/B)+1\log_2(n/B) + 1, ≈log⁡Bn\approx \log_B n, B-tree levels).
  • BST with scattered nodes
  • BST in BFS (level) order
  • BST in van Emde Boas order
  • B-tree
Cold search time versus b=log⁡2Bb = \log_2 B (in units of one transferred key)
  • B-tree
  • BST, one node per block
With latency λ=1000\lambda = 1000, the discrete minimum occurs at B=128B = 128 and the continuous minimum, solving B(ln⁡B−1)=λB(\ln B - 1) = \lambda, at B≈226B \approx 226. At that BB a search costs 3384, versus 20020 for the binary tree (5.9 times more), with a B-tree of 3 levels.
2^20 - 1
64 keys
64 blocks
B-tree node fill
1000
Keys nn1048575
Children per B-tree node64
Levels: BST and B-tree20 and 4
Cached blocks64
Scattered BST / B-tree6.2×
Optimal B (time model)2^7 = 128
Simulate 1,500 random searches (after 1,500 warm-up searches) in a tree with n=2k−1n = 2^k - 1 keys and an LRU cache of M/BM/B blocks, across four structures: a BST with each node in a separate block, a level-order BST, a van Emde Boas layout BST (below) and a B-tree. Each bar's dashed mark is the no-cache theoretical prediction. Increase BB: B-tree and vEB BST costs plunge, while the scattered BST barely moves. Increase MM: cache retains upper levels so they no longer cost transfers, and each bar falls below its mark. The lower curve is cold-search time under a latency +B+ B keys-per-block model: it has a minimum, far below the binary tree with one node per block. Change latency: where does optimal BB move?

Two observations from the interactive deserve emphasis. First, height falls to log⁡Bn\log_B n but comparisons do not: a B-tree makes about log⁡2n\log_2 n comparisons total (binary search in each node costs log⁡2B\log_2 B across log⁡Bn\log_B n nodes), as many as a binary tree. It saves blocks, not comparisons, so a comparison-counting model does not distinguish them. Second, BB 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 ⌈log⁡Bn⌉ (λ+B)\lceil \log_B n \rceil\,(\lambda + B) occurs at BB approximately satisfying B(ln⁡B−1)=λB(\ln B - 1) = \lambda, where λ\lambda is access latency measured in transferred keys: it grows somewhat slower than λ\lambda.

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.

[ ]B-tree with block counter and external mergeBrowser
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 log⁡2(N/M)\log_2(N/M) full passes; wide merging costs log⁡M/B(N/M)\log_{M/B}(N/M), 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 BB. Real hierarchies have many BB at once (cache line, virtual-memory page, disk block), differing across machines. Frigo, Leiserson, Prokop and Ramachandran (1999) proposed algorithms that mention neither MM nor BB yet are optimal for all of them.

This suffices for the whole hierarchy. An algorithm optimal for any MM and BB 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 M=Ω(B2)M = \Omega(B^2), 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 BB apart, each step reaches a new block. In-order layout fails too. The van Emde Boas layout halves a tree of hh levels: store the top tree first (⌊h/2⌋\lfloor h/2 \rfloor levels), followed by each bottom subtree in sequence, recursively applying the same rule to every piece.

InteractiveThe van Emde Boas layout
Tree (each node shows its heap number)12345678910111213141516171819202122232425262728293031Array in van Emde Boas order, in blocks of 3102132438416517697188199510101120122113111422152316617121824192520132126222723724142528262927152830293130
  • path from root to selected leaf
  • one color per block of BB cells
The tree is split halfway up: first the top two levels, then each entire, contiguous three-level subtree below, each split again in the same way. At some recursion level the pieces fit in a block, whatever B is.
Blocks per search in a 12-level tree (4095 nodes) versus b=log⁡2Bb = \log_2 B
  • level order
  • in-order
  • van Emde Boas
  • lower bound log⁡B+1(n+1)\log_{B+1}(n+1)
Array layout
3
6
Blocks touched by this path3
Mean over 16 leaves3.13
Mean: level order, in-order, vEB4.00 / 3.44 / 3.13
Lower bound (worst path) ⌈log⁡B+1(n+1)⌉\lceil\log_{B+1}(n+1)\rceil3
Array blocks11
A perfect five-level tree stored in an array in three orders. Nodes carry heap numbers (1 to 31), and the array below shows the node at each position; colors indicate blocks of BB cells. Choose a leaf and count colors along its path. Try B=2,3,4,…,8B = 2, 3, 4, \dots, 8 with van Emde Boas layout and compare: recursion ensures that at some level tree pieces fit a block for any BB. Below is the same experiment on a 12-level tree, averaging all paths for B=2bB = 2^b: van Emde Boas closely follows lower bound log⁡B+1(n+1)\log_{B+1}(n+1) without knowing BB; the others decrease only like log⁡2(n/B)\log_2(n/B), one block fewer each time BB doubles.
Proof

Measure pieces by levels: a piece of HH levels has 2H−12^H - 1 nodes, and recursion splits it into a top piece of ⌊H/2⌋\lfloor H/2\rfloor levels and bottom pieces of ⌈H/2⌉\lceil H/2\rceil. Fix BB and let qq be the largest integer with 2q−1≤B2^q - 1 \le B, so q+1>log⁡2(B+1)q + 1 > \log_2(B+1). Stop recursion once a piece has at most qq levels (at most BB 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 f(H)f(H) be that number for a piece of HH levels. If H≤qH \le q, f(H)=1f(H) = 1; otherwise the path crosses the top and one bottom piece, and f(H)=f(⌊H/2⌋)+f(⌈H/2⌉)f(H) = f(\lfloor H/2\rfloor) + f(\lceil H/2\rceil). Inductively f(H)≤2H/(q+1)f(H) \le 2H/(q+1) for every H>qH > q. If both halves have at most qq levels, f(H)=2≤2H/(q+1)f(H) = 2 \le 2H/(q+1) because H≥q+1H \ge q + 1. If both exceed qq, sum the induction hypotheses: 2⌊H/2⌋/(q+1)+2⌈H/2⌉/(q+1)=2H/(q+1)2\lfloor H/2\rfloor/(q+1) + 2\lceil H/2\rceil/(q+1) = 2H/(q+1). If only the bottom exceeds qq, then ⌊H/2⌋=q\lfloor H/2\rfloor = q and ⌈H/2⌉=q+1\lceil H/2\rceil = q + 1, giving H=2q+1H = 2q + 1 and f(H)=1+f(q+1)=1+2=3≤2(2q+1)/(q+1)f(H) = 1 + f(q+1) = 1 + 2 = 3 \le 2(2q+1)/(q+1), equivalent to q≥1q \ge 1.

With n≥Bn \ge B nodes, the tree has h=log⁡2(n+1)h = \log_2(n+1) levels. If h≤qh \le q, then n=Bn = B, the path lies within one basic piece and touches at most 2≤4log⁡B+1(B+1)2 \le 4\log_{B+1}(B+1) blocks. If h>qh > q, it crosses at most 2h/(q+1)<2log⁡2(n+1)/log⁡2(B+1)=2log⁡B+1(n+1)2h/(q+1) < 2\log_2(n+1)/\log_2(B+1) = 2\log_{B+1}(n+1) basic pieces and touches at most twice as many blocks: 4log⁡B+1(n+1)4\log_{B+1}(n+1).

∎

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 log⁡B+1(n+1)\log_{B+1}(n+1)), but the bound’s form matters: log⁡Bn\log_B n for all BB 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 O(n)\bigO(n) but is a contiguous memmove, very fast up to large sizes, and search is binary over contiguous memory.

[ ]Sorted list with bisect versus red–black treeBrowser
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:

NeedUseWhy
Membership only, no orderinghash tableO(1)\bigO(1) expected and faster than any tree
Ordered map in RAM, many writesred–black (std::map, TreeMap) or in-memory B-treeO(log⁡n)\bigO(\log n) guaranteed; B-trees win through cache locality
Ordered map in RAM, many readsAVL or sorted list with bisectlower height; the list is unbeatable if it rarely changes
Disk data, range queriesB+^+-treelog⁡BN\log_B N blocks and linked leaves make the range almost free
Next most urgent, no full orderheapdo 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

NumericAverage depth of a random BST
Insert n=1000n = 1000 distinct keys in random order into an empty BST. What is expected node depth (root depth 0), using the theorem's exact formula? Round to two decimals.
QuizWhat does a rotation do?
In tree y(x(A,B),C)y(x(A, B), C), rotate right along the edge between yy and its left child xx. What results, and which subtree changes parent?
QuizRecoloring is a split
Insert a red node with a red parent and red uncle. In the equivalent 2–3–4 tree, what operation corresponds to recoloring (parent and uncle black, grandparent red)?
ProofAVL height bound
Prove: Let N(h)N(h) be the minimum nodes in an AVL tree of height hh (in edges; the empty tree has height −1-1). Then N(h)=Fh+3−1N(h) = F_{h+3} - 1 with F1=F2=1F_1 = F_2 = 1, and every AVL with nn nodes has height h≤log⁡φ(n+1)−1h \le \log_\varphi(n+1) - 1, with φ=(1+5)/2\varphi = (1 + \sqrt5)/2.
0
Calculate N(h)N(h) by recurrence and bound Fibonacci growth.

Step 1 of 4. What does a minimum-node AVL of height hh look like, and what recurrence does N(h)N(h) satisfy?

ProofRed–black height bound
Prove: A red–black tree with nn internal nodes has at most 2log⁡2(n+1)2\log_2(n+1) nodes on every root-to-empty-leaf path.
0
Let b(x)b(x) be the number of black nodes (counting xx) on a path from xx to an empty leaf in its subtree. Rule 3 makes it well-defined.

Step 1 of 4. What is first proved about subtree size?

NumericHeight of a 4 KiB B-tree
B-tree nodes occupy a 4 KiB block and each entry (key plus child pointer) takes 16 bytes, so 256 entries fit: maximum degree is 256 and minimum degree t=128t = 128. What is the height upper bound in edges for n=109n = 10^9 keys? Give the integer ⌊log⁡tn+12⌋\lfloor \log_t\frac{n+1}{2} \rfloor.
NumericExternal merge transfers
Sort N=109N = 10^9 elements with memory of M=107M = 10^7 elements and blocks of B=103B = 10^3. Form runs of size MM and merge M/B−1M/B - 1 at a time in M/B−1M/B - 1-way merges, with one output page. Every pass, including run formation, reads and writes all blocks. How many block transfers are needed in total?
CodeBST range query
Implement rango(raiz, a, b), returning in increasing order all BST keys kk with a≤k≤ba \le k \le b. 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 k+2(h+1)k + 2(h+1) reads, where kk is output size and hh 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 resultado
Shift+Enter to run
QuizWhich structure for each case?
Three needs: (1) an on-disk index of 10910^9 rows with range queries, (2) an in-memory ordered map with few writes and many reads, (3) a set of identifiers requiring membership only, with no order. Which choice is most reasonable in that order?

Summary

Key idea
A search tree is as fast as its height; balancing keeps height logarithmic using local operations (rotations) that preserve order. When data lives in blocks, the right tree exploits the whole block: a B-tree, with height log⁡Bn\log_B n instead of log⁡2n\log_2 n.
  • A BST supports search, insertion, deletion, successor and range in O(h)\bigO(h). Random insertions give average depth 2(n+1)Hn/n−4≈1.39log⁡2n2(n+1)H_n/n - 4 \approx 1.39\log_2 n, 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 ∣altura(izq)−altura(der)∣≤1|\text{altura(izq)} - \text{altura(der)}| \le 1 and has height ≤1.44log⁡2(n+1)−1\le 1.44\log_2(n+1) - 1 (the thinnest are Fibonacci trees); insertion needs at most one repair (single or double rotation), deletion up to Θ(log⁡n)\Theta(\log n).
  • A red–black tree encodes a 2–3–4 tree in binary: recoloring = overflowing-node split, rotation = node rearrangement. Height is ≤2log⁡2(n+1)\le 2\log_2(n+1), 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 Θ(log⁡BN)\Theta(\log_B N), scan N/BN/B and sort Θ(NBlog⁡M/BNB)\Theta(\tfrac{N}{B}\log_{M/B}\tfrac{N}{B}). A B-tree of minimum degree tt has height ≤log⁡tn+12\le\log_t\frac{n+1}{2}, with the same comparisons as a binary tree but far fewer blocks.
  • A cache-oblivious algorithm achieves those costs without knowing MM or BB. The van Emde Boas layout stores a perfect tree in an array so any search touches O(log⁡Bn)\bigO(\log_B n) blocks for all BB simultaneously.