TExcelTAD

How to Augment a Data Structure

The order-statistic tree was a red-black tree plus one integer per node. Most of the data structures used in practice are like that: rarely invented from scratch, usually a textbook structure with some extra information stored in it. This lesson extracts the recipe, proves the theorem that says which extra fields a red-black tree can maintain for free, and shows a field that cannot be maintained, so the boundary is clear.

The four steps

  1. Choose an underlying structure. For ordered data with insertions and deletions, a red-black tree is the usual choice.
  2. Decide what extra information to store. For order statistics it was the subtree size.
  3. Check that the information can be maintained by the structure's operations, insertions, deletions and their rotations, without making them asymptotically slower.
  4. Develop the new operations that use the information, such as OS-SELECT and OS-RANK.

Step 3 is where designs fail, and a general theorem settles it for red-black trees.

The augmentation theorem

Theorem. Let ff be a field of the nodes of a red-black tree on nn nodes, and suppose that x.fx.f can be computed in O(1)O(1) time from the information in xx, x.leftx.\textit{left} and x.rightx.\textit{right} alone, including x.left.fx.\textit{left}.f and x.right.fx.\textit{right}.f. Then insertion and deletion can maintain ff in every node without changing their O(lg⁡n)O(\lg n) running time.

Proof sketch. A change at a node xx can only affect ff at xx and its ancestors: no other node has xx in its subtree. So after changing xx, recompute ff at xx, its parent, its grandparent and so on up to the root, O(lg⁡n)O(\lg n) nodes at O(1)O(1) each, and stop early if a value comes out unchanged.

  • Insertion, first phase: the new node zz is a leaf; its ff depends only on itself and the sentinel. Recompute along the path from zz to the root: O(lg⁡n)O(\lg n).
  • Rotations: a rotation changes the children of exactly two nodes, xx and yy. Recompute ff at the lower one, then at the upper one; no ancestor's subtree changes as a set, so if ff depends only on the subtree (as all fields of this kind do) nothing above needs updating. O(1)O(1) per rotation.
  • Insertion fix-up: recolourings change ff only if ff depends on colours, in which case they propagate upwards like any change; at most two rotations. In total O(lg⁡n)O(\lg n).
  • Deletion: the structural change happens at yy's old position; recompute along the path from there to the root, O(lg⁡n)O(\lg n), plus at most three rotations in the fix-up.

The program shows the theorem at work: a red-black tree whose nodes keep three fields at once (subtree size, sum of keys, maximum key), each recomputed by one pull function, and a query that uses them, the sum of all keys below a threshold. After random insertions it checks every field and the queries against brute force.

python · try it yourself
import random

RED, BLACK = "R", "B"

class Node:
    __slots__ = ("key", "color", "left", "right", "parent", "size", "total", "biggest")
    def __init__(self, key, color, nil):
        self.key, self.color, self.left, self.right, self.parent = key, color, nil, nil, nil
        self.size, self.total, self.biggest = (1, key, key) if key is not None else (0, 0, float("-inf"))

class AugmentedRB:
    def __init__(self):
        self.nil = Node(None, BLACK, None)
        self.root = self.nil
    def pull(self, x):
        """recompute every augmented field of x from x and its two children: O(1)"""
        l, r = x.left, x.right
        x.size = l.size + r.size + 1
        x.total = l.total + r.total + x.key
        x.biggest = max(l.biggest, r.biggest, x.key)
    def rotate(self, x, d):
        nil, o = self.nil, ("right" if d == "left" else "left")
        y = getattr(x, o)
        setattr(x, o, getattr(y, d))
        if getattr(y, d) is not nil: getattr(y, d).parent = x
        y.parent = x.parent
        if x.parent is nil: self.root = y
        elif x is x.parent.left: x.parent.left = y
        else: x.parent.right = y
        setattr(y, d, x)
        x.parent = y
        self.pull(x); self.pull(y)                     # lower node first, then the upper one
    def insert(self, key):
        z, y, x = Node(key, RED, self.nil), self.nil, self.root
        while x is not self.nil:
            y, x = x, (x.left if key < x.key else x.right)
        z.parent = y
        if y is self.nil: self.root = z
        elif key < y.key: y.left = z
        else: y.right = z
        a = y
        while a is not self.nil:                       # recompute along the path to the root
            self.pull(a); a = a.parent
        while z.parent.color == RED:
            p = z.parent; g = p.parent
            a, b = ("left", "right") if p is g.left else ("right", "left")
            u = getattr(g, b)
            if u.color == RED:
                p.color = u.color = BLACK; g.color = RED; z = g; continue
            if z is getattr(p, b):
                z = p; self.rotate(z, a); p = z.parent
            p.color = BLACK; g.color = RED; self.rotate(g, b)
        self.root.color = BLACK
    def sum_below(self, k):
        """sum of all keys < k, in O(lg n) using the subtree totals"""
        s, x = 0, self.root
        while x is not self.nil:
            if x.key < k:
                s += x.left.total + x.key; x = x.right
            else:
                x = x.left
        return s
    def check(self, x=None):
        x = self.root if x is None else x
        if x is self.nil: return 0, 0, float("-inf")
        (n1, s1, m1), (n2, s2, m2) = self.check(x.left), self.check(x.right)
        assert (x.size, x.total, x.biggest) == (n1 + n2 + 1, s1 + s2 + x.key, max(m1, m2, x.key))
        return x.size, x.total, x.biggest

rng = random.Random(31)
t, keys = AugmentedRB(), []
for k in rng.sample(range(10000), 1500):
    t.insert(k); keys.append(k)
t.check()
for q in [0, 2500, 5000, 9999, 10 ** 6]:
    assert t.sum_below(q) == sum(k for k in keys if k < q)
print("all three fields correct in all", t.root.size, "nodes; sum_below agrees with brute force")
print("n =", t.root.size, "| sum of keys =", t.root.total, "| max key =", t.root.biggest,
      "| sum of keys below 5000 =", t.sum_below(5000))
all three fields correct in all 1500 nodes; sum_below agrees with brute force
n = 1500 | sum of keys = 7556577 | max key = 9977 | sum of keys below 5000 = 1798719

pull is the whole augmentation: insertion calls it on the path up and in every rotation, and nothing else changes. Adding a fourth field means adding one line to pull.

A field that cannot be maintained

The theorem's condition, "computed from the node and its children", is essential. Consider storing in each node its rank directly, instead of the subtree size. Then OS-SELECT would be a plain search on ranks and OS-RANK would be a lookup. But inserting a new minimum increases the rank of every node by one: Θ(n)\Theta(n) updates for one insertion. Rank depends on the whole tree to the left of a node, not on its subtree. The same goes for depth (it depends on the ancestors, and one rotation changes the depth of a whole subtree).

python · try it yourself
import random

rng = random.Random(2)
keys = sorted(rng.sample(range(1000, 10 ** 6), 2000))
new_minimum = 5
ranks_before = {k: i + 1 for i, k in enumerate(keys)}
keys_after = sorted(keys + [new_minimum])
ranks_after = {k: i + 1 for i, k in enumerate(keys_after)}
changed = sum(ranks_before[k] != ranks_after[k] for k in keys)
print(f"inserting {new_minimum} into {len(keys)} keys changes the stored rank of {changed} nodes")

# subtree sizes change only on the insertion path: count them in a random BST
class N:
    __slots__ = ("k", "l", "r", "size")
    def __init__(self, k): self.k, self.l, self.r, self.size = k, None, None, 1
root = None
order = keys[:]; rng.shuffle(order)
for k in order:
    if root is None: root = N(k); continue
    x = root
    while True:
        x.size += 1
        if k < x.k:
            if x.l is None: x.l = N(k); break
            x = x.l
        else:
            if x.r is None: x.r = N(k); break
            x = x.r
path = 0
x = root
while x is not None:
    path += 1
    x = x.l if new_minimum < x.k else x.r
print(f"the same insertion changes the subtree size of only {path} nodes (the search path)")
inserting 5 into 2000 keys changes the stored rank of 2000 nodes
the same insertion changes the subtree size of only 7 nodes (the search path)

The comparison is the theorem in one picture: thousands of updates for a field that depends on the whole tree, a handful for a field that depends only on the subtree.

In C++

A compact C++ version of the recipe: a generic red-black insertion where the augmentation is a single pull member, here maintaining subtree sizes and sums so that the tree answers "sum of the kk smallest keys", a prefix sum by rank.

cpp · try it yourself
#include <algorithm>
#include <cstdio>
#include <numeric>
#include <random>
#include <vector>

class SumTree {
    struct Node { long key = 0; bool red = false; int left = 0, right = 0, parent = 0, size = 0; long total = 0; };
    std::vector<Node> t{Node{}};
    int root = 0;
    int& child(int x, bool right) { return right ? t[x].right : t[x].left; }
    void pull(int x) {                                        // the whole augmentation
        t[x].size = t[t[x].left].size + t[t[x].right].size + 1;
        t[x].total = t[t[x].left].total + t[t[x].right].total + t[x].key;
    }
    void rotate(int x, bool left) {
        int y = child(x, left);
        child(x, left) = child(y, !left);
        if (child(y, !left) != 0) t[child(y, !left)].parent = x;
        t[y].parent = t[x].parent;
        if (t[x].parent == 0) root = y;
        else if (x == t[t[x].parent].left) t[t[x].parent].left = y;
        else t[t[x].parent].right = y;
        child(y, !left) = x;
        t[x].parent = y;
        pull(x); pull(y);
    }
public:
    void insert(long key) {
        int y = 0, x = root;
        while (x != 0) { y = x; x = key < t[x].key ? t[x].left : t[x].right; }
        t.push_back({key, true, 0, 0, y, 1, key});
        int z = static_cast<int>(t.size()) - 1;
        if (y == 0) root = z; else if (key < t[y].key) t[y].left = z; else t[y].right = z;
        for (int a = y; a != 0; a = t[a].parent) pull(a);
        while (t[t[z].parent].red) {
            int p = t[z].parent, g = t[p].parent;
            bool left = p == t[g].left;
            int u = child(g, left);
            if (t[u].red) { t[p].red = t[u].red = false; t[g].red = true; z = g; continue; }
            if (z == child(p, left)) { z = p; rotate(z, left); p = t[z].parent; }
            t[p].red = false; t[g].red = true;
            rotate(g, !left);
        }
        t[root].red = false;
    }
    long sum_smallest(int k) const {                          // sum of the k smallest keys
        long s = 0;
        int x = root;
        while (x != 0 && k > 0) {
            int l = t[x].left;
            if (k <= t[l].size) x = l;
            else { s += t[l].total + t[x].key; k -= t[l].size + 1; x = t[x].right; }
        }
        return s;
    }
};

int main() {
    std::mt19937 rng(31);
    std::vector<long> keys(50000);
    std::iota(keys.begin(), keys.end(), 1);
    std::shuffle(keys.begin(), keys.end(), rng);
    SumTree tree;
    for (long k : keys) tree.insert(k);
    bool ok = true;
    for (long k : {0L, 1L, 10L, 12345L, 50000L}) ok = ok && tree.sum_smallest(static_cast<int>(k)) == k * (k + 1) / 2;
    std::printf("sum of the 12345 smallest of 1..50000: %ld; all checks %s\n", tree.sum_smallest(12345), ok ? "pass" : "fail");
}
sum of the 12345 smallest of 1..50000: 76205685; all checks pass

Since the keys are 1,…,500001, \ldots, 50000, the sum of the kk smallest is k(k+1)/2k(k+1)/2, which the program uses as its check.

Test yourself

Which field can a red-black tree maintain in O(lg⁡n)O(\lg n) per update by the augmentation theorem?

  1. the depth of each node
  2. the rank of each node
  3. the maximum key in each node's subtree
  4. the number of nodes with smaller keys anywhere in the tree

After a rotation, in which order should the augmented fields of the two rotated nodes be recomputed?

  1. the upper node first
  2. the node that is now lower first, then its new parent
  3. it does not matter
  4. all ancestors first

Why does inserting a new minimum make stored ranks expensive to maintain?

  1. because the tree must rotate nn times
  2. because every existing node's rank increases by one, Θ(n)\Theta(n) updates
  3. because ranks are not integers
  4. it does not: ranks are cheap