Sub topic 13
Compressed Tries and Radix Trees
This chapter assumes you have read the earlier chapters on the dictionary-based trie, its is_end marker, and its memory costs. You should also be comfortable with Python slicing and dictionaries.
The problem: long single-child chains
A plain trie spends one node per character. Words like "internationalization" that share no prefix with other keys create a chain of nodes with exactly one child each. Each node carries a dictionary, so these chains waste memory and force a pointer hop per character.
A compressed trie merges each chain into a single edge. A radix tree (also called a Patricia tree) is the common form. Every edge is labeled with a string instead of one character, and every internal node that is not a word end has at least two children.
Compressing an example
Take the words car, card, care, and cat. A plain trie uses 7 nodes below the root (c, a, r, d, e, t, plus none shared beyond that). The radix tree uses 5 nodes in total.
The node reached by ca is not a word end. It exists only because the paths to car and cat diverge there. The node for car is a word end and also has children.
Implementation
Each node maps the first character of an edge label to a pair (label, child). Two edges leaving one node never start with the same character, so that first character identifies the edge.
class RadixNode:
def __init__(self):
self.children = {} # first char -> (label, child node)
self.is_end = False
class RadixTree:
def __init__(self):
self.root = RadixNode()
def insert(self, word):
node, rest = self.root, word
while True:
if not rest:
node.is_end = True
return
entry = node.children.get(rest[0])
if entry is None:
leaf = RadixNode()
leaf.is_end = True
node.children[rest[0]] = (rest, leaf)
return
label, child = entry
k = 0
while k < min(len(label), len(rest)) and label[k] == rest[k]:
k += 1
if k < len(label): # partial match: split the edge
mid = RadixNode()
mid.children[label[k]] = (label[k:], child)
node.children[rest[0]] = (label[:k], mid)
child = mid
node, rest = child, rest[k:]
def search(self, word):
node, rest = self.root, word
while rest:
entry = node.children.get(rest[0])
if entry is None:
return False
label, child = entry
if not rest.startswith(label):
return False
node, rest = child, rest[len(label):]
return node.is_end
def starts_with(self, prefix):
node, rest = self.root, prefix
while rest:
entry = node.children.get(rest[0])
if entry is None:
return False
label, child = entry
if label.startswith(rest): # prefix ends inside this edge
return True
if not rest.startswith(label):
return False
node, rest = child, rest[len(label):]
return True
t = RadixTree()
for w in ["car", "card", "care", "cat"]:
t.insert(w)
print(t.search("ca"), t.starts_with("ca"), t.search("care"), t.starts_with("cab"))
# False True True FalseThe key step is the edge split. Inserting cat into a tree that holds the edge car finds a shared part of length 2. The code replaces car with ca, adds a middle node, and hangs the old remainder r below it. The loop then continues from the middle node and adds the new leaf for t.
What changes compared with a plain trie
| Aspect | Plain trie | Radix tree |
|---|---|---|
| Edge label | One character | One or more characters |
| Node count | Up to the total characters stored | At most about 2 × number of words |
| Prefix check | Stop at a node | May stop in the middle of an edge |
| Insert | Create nodes | Create nodes or split an edge |
The time cost is still O(L) for a key of length L, because comparing labels examines each character at most once. The gain is in memory and in pointer hops, not in the big-O class.
Gotchas
- A prefix can end inside an edge.
starts_with("ca")must succeed even when the next edge is labeledcar. Comparing only whole labels gives wrong answers. - Deletion must undo splits. After removing
cat, the nodecahas one child and is not a word end, so it should merge with its remaining edge to restorecar. - Slicing strings creates copies. Production implementations often store
(start, end)offsets into the original word.
Exercise
Starting from an empty radix tree, you insert "test", then "team". What is the label on the edge from the root, and what are the labels on the two edges below the node it reaches?
Show answer
The first insert creates one edge labeled "test". Inserting "team" shares "te" with it, so the edge is split. The root edge is labeled "te", and the node below has two edges, "st" and "am".