Keys As Paths
A trie stores a set of strings by making each key a path from the root. One edge carries one symbol, and the node reached by following c, a, t is the node for the prefix "cat". A key is present when its path exists and the node at the end is marked terminal.
Keys that share a prefix share the nodes for that prefix. "cat", "car", and "cart" share the nodes for c and a, so the three keys need five nodes below the root rather than ten stored characters. Navigation dispatches on one symbol at a time, so a lookup never compares the query against a stored key; the edges that exist along the way decide the answer.
The Node Record
The simplest node is an array of child pointers indexed by symbol, plus one flag. The node stores no characters: the symbol an edge represents is the index of the slot in its parent that points to it.
typedef struct node {
struct node *child[26]; // one slot per letter, NULL if absent
bool terminal; // a key ends at this node
} node;On a 64-bit machine that is 208 bytes of pointers per node, nearly all of them null once the trie is more than two levels deep. A map rather than a set stores its value beside the flag. Every layout later in this chapter is a different answer to how those 26 slots should be represented.
Walking A Lookup
Looking up "car" reads c and takes the c edge, which discards "dog" and every other key starting with d without examining them. It reads a, then r, and stops with the key spent at a node marked terminal.
bool contains(const node *n, const char *key) {
for (; *key; key++) {
n = n->child[*key - 'a'];
if (!n) return false; // missing edge: absent
}
return n->terminal; // key spent: does a key end here?
}The two exits are the two ways to miss. "cot" fails at depth two because no o edge leaves the "c" node. "ca" walks a real path but ends at a node with no terminal mark: it is a prefix of stored keys, not a stored key.
Insertion And Deletion
Insertion walks the lookup path, allocating a node wherever the edge is missing, and marks the last node terminal. Deletion clears the mark and frees nodes on the way back up while they have neither a mark nor a child.
void insert(node *n, const char *key) {
for (; *key; key++) {
node **c = &n->child[*key - 'a'];
if (!*c) *c = calloc(1, sizeof(node));
n = *c;
}
n->terminal = true;
}
bool erase(node *n, const char *key) { // true: caller frees n
if (!*key) n->terminal = false;
else {
node **c = &n->child[*key - 'a'];
if (*c && erase(*c, key + 1)) { free(*c); *c = NULL; }
}
return !n->terminal && no_children(n);
}All three operations cost O(m) for a key of length m, independent of how many keys are stored, which no comparison-based structure such as the red-black tree can offer.
Node Fan-Out And Memory
A child array over 256 byte values costs 2 KB of pointers per node, whether the node has one child or two hundred, and gives O(1) child selection. A sorted list of occupied symbols costs bytes proportional to the real children but selects a child by scan or binary search in O(log σ).
The waste concentrates near the leaves. In a trie over natural-language words most nodes below the second level have a single child, so a full array stores one pointer and 255 nulls. A naïve trie can occupy an order of magnitude more memory than the concatenated keys. Path compression, level compression, and adaptive nodes are the three responses, and space rather than time is the constraint each addresses.
Path Compression
Path compression collapses every chain of single-child nodes into one edge that carries the whole substring. The result is a radix tree, or a Patricia trie after Morrison's 1968 binary formulation. Lookup now compares a label, not one symbol, per step.
bool contains(const rnode *n, const char *key, size_t m) {
while (m > 0) {
n = n->child[(uint8_t)key[0]];
if (!n || n->len > m || memcmp(n->label, key, n->len))
return false;
key += n->len;
m -= n->len;
}
return n->terminal;
}Every internal node now has at least two children, so n keys produce at most n − 1 internal nodes regardless of key length. The label comparison is one memcmp over contiguous bytes instead of a pointer dereference per symbol.
Splitting An Edge
Insertion into a radix tree has one hard case. Inserting "romulus" when an edge is labelled "romane" matches three bytes and then diverges inside the label, where no node exists to branch from. The edge must be split at the divergence point.
// key shares k bytes with the edge, and 0 < k < n->len
rnode *mid = new_node(n->label, k); // "rom"
n->label += k; n->len -= k; // old edge keeps "ane"
mid->child[(uint8_t)n->label[0]] = n;
parent->child[(uint8_t)mid->label[0]] = mid;
if (k == m) mid->terminal = true; // the key ends at the split
else attach(mid, leaf(key + k, m - k)); // new edge "ulus"The other cases are simple: a fully matched label continues the descent, and a missing child gets a leaf carrying the whole remainder. Deletion reverses the split, merging a non-terminal node left with one child into that child by concatenating labels.
Level Compression
Level compression attacks depth where branching is dense. If the top k levels of a binary trie are nearly full, they become one node of 2^k children indexed by the next k bits. Nilsson and Karlsson's 1999 LC-trie combines this with path compression in a flat array.
node = t[0];
pos = SKIP(node);
branch = BRANCH(node);
adr = ADR(node);
while (branch != 0) { // internal node
node = t[adr + EXTRACT(pos, branch, s)]; // k bits, one read
pos += branch + SKIP(node);
branch = BRANCH(node);
adr = ADR(node);
}
// leaf: compare the stored string, since skipped bits were never checkedOne array read consumes k levels. Skipped bits are not compared during descent, so the leaf verifies the whole key once. The Linux kernel's IPv4 forwarding table is an LC-trie; a full BGP view of about 800,000 routes resolves in roughly 50 ns using around 64 MiB.
Adaptive Node Layouts
The adaptive radix tree of Leis, Kemper, and Neumann lets each node pick its representation by child count — 4, 16, 48, or 256 — and promotes or demotes it as the count crosses a boundary.
node *find_child(node *n, uint8_t b) {
switch (n->type) {
case NODE4: // scan 4 keys
for (int i = 0; i < n->count; i++)
if (N4(n)->key[i] == b) return N4(n)->child[i];
return NULL;
case NODE16: // one SIMD compare
return simd_find16(N16(n), b);
case NODE48: { // byte index, 48 pointers
uint8_t i = N48(n)->index[b];
return i ? N48(n)->child[i - 1] : NULL;
}
case NODE256:
return N256(n)->child[b];
}
}A node with three children costs four key bytes and four pointers instead of 256 pointers. Node48 keeps O(1) selection with a 256-byte index into 48 slots. With path compression, overhead per key stays near that of a hash table while keys remain sorted.
Prefix Enumeration
Every key in the subtree under a node begins with that node's prefix, and no key outside it does. Autocomplete is therefore a descent to the prefix node followed by a traversal of its subtree.
void collect(const node *n, char *buf, int depth) {
if (n->terminal) { buf[depth] = 0; emit(buf); }
for (int c = 0; c < 26; c++) // symbol order: sorted output
if (n->child[c]) {
buf[depth] = 'a' + c;
collect(n->child[c], buf, depth + 1);
}
}The cost is O(p) to reach the prefix plus the size of the subtree, which is bounded by the total length of the keys reported. Visiting children in symbol order produces sorted output, so the same walk serves range scans and successor queries. Ranked completions store the best score in each subtree and descend greedily against it.
Longest-Prefix Match
IP forwarding asks which stored prefix is the longest one the destination address begins with, since 10.0.0.0/8 and 10.1.0.0/16 may both be installed and the more specific route must win. A binary trie answers by descending on address bits and remembering the last node that carried a route.
const route *lpm(const bnode *n, uint32_t addr) {
const route *best = NULL;
for (int bit = 31; n; bit--) {
if (n->route) best = n->route; // longest match so far
if (bit < 0) break; // all 32 bits consumed
n = n->child[(addr >> bit) & 1];
}
return best;
}One descent of at most 32 steps answers the query. A hash table would need one probe per installed prefix length, and an ordered index such as a skip list a predecessor search followed by a prefix check.
Aho-Corasick Failure Links
Matching many patterns in one pass of a text starts from a trie of the patterns. Each node gets a failure link to the node for the longest proper suffix of its string that is also a prefix in the trie. For patterns he, she, his, and hers, the node for "she" links to "he".
root->fail = root; push(q, root);
while ((u = pop(q))) { // BFS: links point to shallower nodes
for (int c = 0; c < SIGMA; c++) {
node *v = u->child[c];
if (!v) continue;
node *f = u->fail;
while (f != root && !f->child[c]) f = f->fail;
v->fail = (u != root && f->child[c]) ? f->child[c] : root;
v->out = v->terminal ? v : v->fail->out;
push(q, v);
}
}The out pointer names the nearest pattern ending on the failure chain, so matches hidden inside longer ones are reported.
Multi-Pattern Matching
The scan keeps one current state. On each symbol it takes the matching edge if one exists; otherwise it follows failure links until one does or it reaches the root. The input position never moves backward.
node *s = root;
for (size_t i = 0; i < n; i++) {
int c = text[i];
while (s != root && !s->child[c]) s = s->fail;
if (s->child[c]) s = s->child[c];
for (node *o = s->out; o; o = o->fail->out)
report(o, i);
}Scanning "ushers" reaches "she" at the e and reports both she and he, falls back to "he" on the r, and reports hers at the end. Each failure step lowers the depth, which rises by at most one per symbol, so the scan costs O(t + z) for text length t and z matches, whatever the number of patterns.
Comparison With Hash Tables
A hash table lookup is often quoted as O(1) against a trie's O(m). For string keys that is wrong: hashing reads all m bytes and a hit compares the full key, so the hash path also touches Θ(m) bytes. The difference is access pattern. The hash table reads the key in two contiguous passes, while the trie reads it once but chases a pointer, and risks a cache miss, per level.
The trie earns its place on what a hash table cannot do at all: ordered iteration, prefix and range queries, longest-prefix match, and no collision-driven worst case. For exact membership alone, a hash table, optionally behind a Bloom filter, is the smaller structure.
Engineering Trade-offs
A trie gives O(m) lookup, insertion, and deletion independent of the key count, output-sensitive prefix enumeration, longest-prefix match in one descent, sorted iteration, and no hash function to choose or attack. Shared prefixes are stored once, which removes much of the redundancy in URL sets, routing tables, and dictionaries.
The costs are memory and locality. An uncompressed trie spends most of its bytes on null child slots, and every level is a dependent load the prefetcher cannot anticipate. Radix edges, level compression, and adaptive nodes each recover part of that, at the price of edge splitting, node promotion, and code considerably harder to get right than the array-of-children version.
Applications
The Linux kernel stores the IPv4 forwarding table as an LC-trie in net/ipv4/fib_trie.c, and every route lookup on the host is a longest-prefix match against it. Redis's radix tree, rax, indexes each stream by entry ID and holds consumer-group pending-entries lists. DuckDB builds an adaptive radix tree for every index, enforcing primary-key and unique constraints and serving equality and range filters, and persists the ART to disk instead of rebuilding it on load.
Apache Lucene stores its term dictionary as a finite-state transducer, a trie that also shares suffixes; a Wikipedia index with 9.8 million distinct terms compiles to a 69 MB FST. ClamAV's libclamav/matcher-ac.c scans files against its signature set with an Aho-Corasick automaton.
Summary
A trie makes each key a path over the alphabet, so lookup, insertion, and deletion cost O(m) in the key length and never depend on how many keys are stored. The subtree under any node is exactly the set of keys with that prefix, one descent that remembers the last terminal node answers longest-prefix match, and failure links turn the same tree into a multi-pattern matcher.
The price is per-node overhead and a dependent memory access per level. Path compression bounds internal nodes at n − 1 at the cost of edge splitting, level compression trades memory for depth where branching is dense, and adaptive node types size each node to its real child count.