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 words leave at most 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 strings leave at most nodes, and at most when the root branches.
- Store edge labels as references into the strings, for machine words of space plus the strings themselves.
- Run Patricia search and insertion over the bits of keys, prove that keys give exactly 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, , and how they differ.
Collapsing single-child chains
(root)
└── sl
├── e
│ ├── d sled
│ └── ep sleep
├── id slid
│ └── e slide
└── ow slow
├── er slower
└── ly slowlyThe 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.
Let the radix tree of nonempty strings have nodes. Every node other than the root either ends a word (the set , with ) or has at least two children (the set ); a leaf always ends a word. Counting nodes:
A tree with nodes has edges, one per child. Nodes in have at least 2 children, the root at least 1:
Substituting the first line gives , hence the bound. If the root has two or more children, the same count gives .
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 machine words besides the strings, against up to nodes for the plain trie. Searching for still costs 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.
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 , for keys that are bit strings none of which is a prefix of another, such as distinct -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.
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 rootLeaves are the keys themselves. Insertion first finds the closest stored key ; every key below the insertion point agrees with on all bits above , so the new node, testing bit , separates from all of them at once. Bernstein's crit-bit trees are the same structure.
| random keys | Trie: simulated | Trie: formula | Patricia: simulated | Patricia: formula |
|---|---|---|---|---|
| 1,000 | 11.30 | 11.30 | 10.29 | 10.30 |
| 10,000 | 14.62 | 14.62 | 13.62 | 13.62 |
| 100,000 | 17.94 | 17.94 | 16.94 | 16.94 |
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.
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 bestWith 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.
With the same four routes, where does a packet for 10.1.3.7 go?
- C, because 10.1.2.0/24 is the most specific route
- B
- A
- 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 levels of a complete subtree by a single node with 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 is the radix tree of all suffixes of , with a unique end marker . The marker makes the set prefix-free, so the suffixes are exactly the leaves, and by the theorem the tree has at most nodes, against for the uncompressed trie of the suffixes.
| , | Suffix trie nodes, | Suffix tree nodes, | |
|---|---|---|---|
| 2 | 5 | 14 | 8 |
| 4 | 9 | 34 | 16 |
| 8 | 17 | 98 | 32 |
| 16 | 33 | 322 | 64 |
Key takeaways
- A radix tree deletes unary nodes that end no word and labels edges with strings: words leave at most nodes ( if the root branches), in words of space plus the strings.
- Patricia is the radix tree of binary keys: exactly 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 in a trie and exactly one bit test less in Patricia, up to tiny fluctuations, with against 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 , with at most nodes instead of .
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
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?
- A
- C
- D
- 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.
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?
- 9,001
- 1,999
- 1,000
- 26,000
Show the answer
B. 1,999
At most branching nodes that end no word, plus at most 1,000 word nodes, plus the root: , whatever the lengths of the words.
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?
- Their heights
- The bit tested at the root
- The number of internal nodes
- 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.
A Patricia search for reaches a leaf holding key . Before answering "present", what must it still do, and why?
- Nothing: reaching a leaf proves that is stored
- Compare with in full, because the bits that no node tests were never checked
- Walk back to the root to confirm every tested bit
- Check 's sibling, because may be stored there
Show the answer
B. Compare with 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 , so one full comparison is needed, and it is also enough: 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).