Simple Algorithm
Algorithms & Data Structures · Optimal · 24 min

Compressed Tries: Radix Trees & Patricia

Collapsing chains of single children, from IP routing to suffix trees.

A trie of an English word list is mostly single-child chains: past the first few letters of a long word, usually only that word continues. A radix tree collapses every such chain into one edge, so kk words leave at most 2k2k nodes, however long they are. Applied to bits, the same idea is Morrison's Patricia, long the heart of BSD's routing table; applied to every suffix of a string, it is the suffix tree.

What you’ll learn

  • Define the compressed trie and prove that kk strings leave at most 2k2k nodes, and at most 2k−12k - 1 when the root branches.
  • Store edge labels as references into the strings, for O(k)O(k) machine words of space plus the strings themselves.
  • Run Patricia search and insertion over the bits of keys, prove that nn keys give exactly n−1n - 1 internal nodes, and explain the final full comparison.
  • Implement longest-prefix match for IP routing, and place LC-tries, adaptive radix trees and suffix trees in the same family.
  • State the average depth of random tries and Patricia tries, log⁡2n+O(1)\log_2 n + O(1), and how they differ.

Collapsing single-child chains

text
(root)
└── sl
    ├── e
    │   ├── d        sled
    │   └── ep       sleep
    ├── id           slid
    │   └── e        slide
    └── ow           slow
        ├── er       slower
        └── ly       slowly

The radix tree of slow, slower, slowly, sleep, sled, slide and slid: 10 nodes counting the root, against 16 in the plain trie. Nodes where a word ends keep it beside them; "slid" and "slow" end at nodes that also have children.

DerivationTheorem: k strings leave at most 2k nodes
  1. N=1+∣B∣+∣W∣N = 1 + \abs{B} + \abs{W}

    Let the radix tree of kk nonempty strings have NN nodes. Every node other than the root either ends a word (the set WW, with ∣W∣≤k\abs{W} \le k) or has at least two children (the set BB); a leaf always ends a word. Counting nodes:

  2. N−1  =  ∑v#children(v)  ≥  2∣B∣+1N - 1 \;=\; \sum_{v} \#\mathrm{children}(v) \;\ge\; 2\abs{B} + 1

    A tree with NN nodes has N−1N - 1 edges, one per child. Nodes in BB have at least 2 children, the root at least 1:

  3. N  ≤  1+(k−1)+k=2kandN≤2k−1 if the root branchesN \;\le\; 1 + (k - 1) + k = 2k \qquad\text{and}\qquad N \le 2k - 1 \ \text{if the root branches}

    Substituting the first line gives ∣B∣≤∣W∣−1≤k−1\abs{B} \le \abs{W} - 1 \le k - 1, hence the bound. If the root has two or more children, the same count gives ∣B∣≤∣W∣−2\abs{B} \le \abs{W} - 2.

The labels are not copied: an edge stores a reference (word index, start, length) into one of the stored strings. A radix tree therefore needs O(k)O(k) machine words besides the strings, against up to 1+∑∣w∣1 + \sum \abs{w} nodes for the plain trie. Searching for xx still costs O(∣x∣)O(\abs{x}) character comparisons. Inserting may split an edge: the new word follows a label partway, then diverges, and a new node appears at the point of divergence.

Predict before you look

The plain trie of the words to, tea, ted, ten, inn and in has 10 nodes, counting the root. How many nodes, counting the root, does its radix tree have?

Show the answer

9

Only "i" disappears: it has one child and ends no word, so the root's edge becomes "in". Every other node survives: "t" has two children (o, e), "te" has three (a, d, n), and to, tea, ted, ten, in and inn end words. Compression pays off on long unbranched chains; on short words with many branches it saves little.

Patricia: compressed binary tries

Patricia (Morrison, 1968: Practical Algorithm To Retrieve Information Coded in Alphanumeric) is the radix tree over the alphabet {0,1}\{0, 1\}, for keys that are bit strings none of which is a prefix of another, such as distinct ww-bit integers. Without unary nodes and with every key at a leaf, every internal node has exactly two children.

Patricia stores no edge labels at all. Each internal node keeps only the index of the bit it tests, the first bit on which the keys below it disagree. A search reads just those bits, so it reaches a leaf whose key agrees with the query on the tested bits, and nothing else is known: one full comparison at the end decides membership.

python
class Node:                          # tests bit number `bit` (w - 1 is the most significant)
    def __init__(self, bit, zero, one):
        self.bit, self.kid = bit, [zero, one]

def find_leaf(root, x):              # follow only the tested bits
    v = root
    while isinstance(v, Node):
        v = v.kid[(x >> v.bit) & 1]
    return v

def contains(root, x):
    return root is not None and find_leaf(root, x) == x    # one full comparison

def insert(root, x):
    if root is None:
        return x
    y = find_leaf(root, x)
    if y == x:
        return root
    b = (x ^ y).bit_length() - 1     # highest bit where x differs from y
    parent, v = None, root
    while isinstance(v, Node) and v.bit > b:   # stop above the first node testing a lower bit
        parent, v = v, v.kid[(x >> v.bit) & 1]
    new = Node(b, v, x) if (x >> b) & 1 else Node(b, x, v)
    if parent is None:
        return new
    parent.kid[(x >> parent.bit) & 1] = new
    return root

Leaves are the keys themselves. Insertion first finds the closest stored key yy; every key below the insertion point agrees with xx on all bits above bb, so the new node, testing bit bb, separates xx from all of them at once. Bernstein's crit-bit trees are the same structure.

nn random keysTrie: simulatedTrie: formulaPatricia: simulatedPatricia: formula
1,00011.3011.3010.2910.30
10,00014.6214.6213.6213.62
100,00017.9417.9416.9416.94
Average depth of a stored key, in a simulation with uniformly random 64-bit keys, against the formulas below. A trie here creates a leaf as soon as one key is left in a subtree.

Longest-prefix match: how routers use tries

A router's forwarding table maps address prefixes such as 10.1.0.0/16 (the addresses whose first 16 bits are those of 10.1) to next hops, and a packet must leave through the route with the longest prefix that matches its destination. In a binary trie of the route prefixes this is one walk down the address bits that remembers the last node carrying a route: at most 32 steps for IPv4 and 128 for IPv6, whatever the size of the table.

python
import ipaddress

def build(routes):                       # routes: {"10.1.0.0/16": "B", ...}
    trie = [[None, None, None]]          # node: [child 0, child 1, next hop]
    for prefix, hop in routes.items():
        net = ipaddress.ip_network(prefix)
        bits, v = int(net.network_address), 0
        for i in range(net.prefixlen):
            b = (bits >> (31 - i)) & 1
            if trie[v][b] is None:
                trie[v][b] = len(trie)
                trie.append([None, None, None])
            v = trie[v][b]
        trie[v][2] = hop
    return trie

def lookup(trie, addr):                  # next hop of the longest matching prefix
    bits, v = int(ipaddress.ip_address(addr)), 0
    best = trie[0][2]
    for i in range(32):
        v = trie[v][(bits >> (31 - i)) & 1]
        if v is None:
            break
        if trie[v][2] is not None:
            best = trie[v][2]
    return best

With the routes 0.0.0.0/0 → default, 10.0.0.0/8 → A, 10.1.0.0/16 → B and 10.1.2.0/24 → C, the lookups give 10.1.2.3 → C, 10.1.9.9 → B, 10.200.0.1 → A and 11.0.0.1 → default.

Check your understanding

With the same four routes, where does a packet for 10.1.3.7 go?

  1. C, because 10.1.2.0/24 is the most specific route
  2. B
  3. A
  4. The default route
Show the answer

B. B

The third byte is 3, not 2, so 10.1.2.0/24 does not match; the walk falls off the trie inside that route's subtree. The longest prefix that does match is 10.1.0.0/16, which the walk remembered on the way down.

Real tables hold hundreds of thousands of routes, and every lookup must finish in nanoseconds, so routers compress the trie two ways:

  • Path compression skips unary chains. The 4.3BSD-Reno release of Berkeley Unix forwarded packets with a Patricia-style binary radix tree (Sklower, 1991), and BSD systems kept that design for decades.
  • Level compression replaces the top ii levels of a complete subtree by a single node with 2i2^i children, so a lookup takes a handful of memory accesses. Nilsson and Karlsson's LC-trie (1999) does both, and Linux's IPv4 forwarding table (fib_trie) is based on it.

Radix trees in systems, and the suffix tree

Main-memory databases index keys with byte-wise radix trees. The adaptive radix tree (ART; Leis, Kemper & Neumann, 2013) branches on one byte per level, uses four node types sized for 4, 16, 48 and 256 children so sparse nodes stay small, and adds path compression. Unlike a hash table it keeps keys in order, so a range scan is a walk. HOT (Binna et al., 2018) varies the number of bits each node inspects to keep the tree shallow. The Linux kernel indexed its page cache with a radix tree for years; since Linux 4.20 (2018) it goes through the XArray, an array-like interface to the same kind of tree.

The most famous radix tree indexes text. The suffix tree of ss is the radix tree of all suffixes of s$s\$, with a unique end marker $\$. The marker makes the set prefix-free, so the n+1n + 1 suffixes are exactly the leaves, and by the theorem the tree has at most 2(n+1)−12(n + 1) - 1 nodes, against Θ(n2)\Theta(n^2) for the uncompressed trie of the suffixes.

kks=akbk$s = a^k b^k\$, ∣s∣\abs{s}Suffix trie nodes, (k+1)2+2k+1(k + 1)^2 + 2k + 1Suffix tree nodes, 4k4k
25148
493416
8179832
163332264
Every distinct substring of akbk$a^k b^k\$ is a node of the suffix trie, and there are Θ(k2)\Theta(k^2) of them; the suffix tree keeps only leaves and branching nodes.

Key takeaways

  • A radix tree deletes unary nodes that end no word and labels edges with strings: kk words leave at most 2k2k nodes (2k−12k - 1 if the root branches), in O(k)O(k) words of space plus the strings.
  • Patricia is the radix tree of binary keys: exactly n−1n - 1 internal nodes, each storing only the bit it tests, a shape fixed by the key set, and a search that ends with one full comparison.
  • Random keys give an average depth of log⁡2n+γ/ln⁡2+12\log_2 n + \gamma/\ln 2 + \tfrac12 in a trie and exactly one bit test less in Patricia, up to tiny fluctuations, with 1.44 n1.44\,n against n−1n - 1 internal nodes.
  • Longest-prefix match is a walk down a binary trie of route prefixes that remembers the last route seen; routers compress it by paths (BSD's Patricia) and by levels (the LC-trie behind Linux's fib_trie).
  • The same compression gives adaptive radix trees in databases and the suffix tree, the radix tree of all suffixes of s$s\$, with at most 2n+12n + 1 nodes instead of Θ(n2)\Theta(n^2).

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

A routing table holds 0.0.0.0/0 → D, 192.168.0.0/16 → A, 192.168.4.0/22 → B and 192.168.5.0/24 → C. Where does a packet for 192.168.6.1 go?

  1. A
  2. C
  3. D
  4. B
Show the answer

D. B

A /22 fixes the first 22 bits, so 192.168.4.0/22 covers 192.168.4.0 through 192.168.7.255, which contains 192.168.6.1. It is longer than the /16 and the /0 that also match; the /24 covers only 192.168.5.x.

Question 2

A radix tree stores 1,000 distinct words with a total length of 9,000 characters, and its root has at least two children. What is the largest number of nodes it can have, counting the root?

  1. 9,001
  2. 1,999
  3. 1,000
  4. 26,000
Show the answer

B. 1,999

At most ∣W∣−2≤998\abs{W} - 2 \le 998 branching nodes that end no word, plus at most 1,000 word nodes, plus the root: 2k−1=19992k - 1 = 1999, whatever the lengths of the words.

Question 3

You insert the same set of 64-bit keys into a Patricia trie in two different orders. What can differ between the two resulting tries?

  1. Their heights
  2. The bit tested at the root
  3. The number of internal nodes
  4. Nothing: the trie is determined by the set of keys
Show the answer

D. Nothing: the trie is determined by the set of keys

A Patricia trie is the compressed binary trie of the key set, and that object is defined without reference to any order. This is unlike a binary search tree, whose shape depends heavily on insertion order.

Question 4

A Patricia search for xx reaches a leaf holding key yy. Before answering "present", what must it still do, and why?

  1. Nothing: reaching a leaf proves that xx is stored
  2. Compare xx with yy in full, because the bits that no node tests were never checked
  3. Walk back to the root to confirm every tested bit
  4. Check yy's sibling, because xx may be stored there
Show the answer

B. Compare xx with yy in full, because the bits that no node tests were never checked

Patricia skips the bits on which all the keys below a node agree. A query can differ from them exactly there and still be routed to yy, so one full comparison is needed, and it is also enough: xx can only be stored at the leaf its tested bits lead to.

Further reading

  • D. R. Morrison, "PATRICIA: practical algorithm to retrieve information coded in alphanumeric," Journal of the ACM 15(4) (1968), 514–534.
  • D. E. Knuth, The Art of Computer Programming, vol. 3, Sorting and Searching, 2nd ed. (Addison-Wesley, 1998), section 6.3.
  • P. Flajolet & R. Sedgewick, "Digital search trees revisited," SIAM Journal on Computing 15(3) (1986), 748–767.
  • S. Nilsson & G. Karlsson, "IP-address lookup using LC-tries," IEEE Journal on Selected Areas in Communications 17(6) (1999), 1083–1092.
  • V. Leis, A. Kemper & T. Neumann, "The adaptive radix tree: ARTful indexing for main-memory databases," Proceedings of ICDE (2013).