Tries: trees of letters
About this lesson
The search trees in this module compare whole keys. A trie does something different: it splits each string into letters and stores one letter per level, so words that start the same share a path. Insert cat, car, cart and dog into a real Python trie, look up cart, cap and ca, and list every word that starts with ca. Each node's children live in a Python dict, covered in the Python lesson "Dictionaries and sets" and the Software lesson "Hash maps: finding things by key"; the Software lesson "Trees" covers the basic tree vocabulary.
A tree whose links are letters
A trie is a tree for strings. Each node keeps kids, a dict from one letter to a child node, and end, a flag. The root stands for the empty string. Walking down spells a word, one letter per level.
class Node:
def __init__(self):
self.kids = {} # letter -> child Node
self.end = False # True if a word ends here
root = Node() # the empty string ""
child of node p under letter ch = the prefix p + ch
words to store: "cat", "car", "cart", "dog"Read the lesson step by step
A tree whose links are letters
A trie is a tree for strings. Each node keeps kids, a dict from one letter to a child node, and end, a flag. The root stands for the empty string. Walking down spells a word, one letter per level.
class Node: def __init__(self): self.kids = {} # letter -> child Node self.end = False # True if a word ends here root = Node() # the empty string "" child of node p under letter ch = the prefix p + ch words to store: "cat", "car", "cart", "dog"Insert cat: three new nodes
insert(root, "cat"): the root has no 'c' child, so line 5 makes one, then line 6 steps down to it. Same for 'a' and 't'. Line 7 sets end = True on the last node: the gold dot means a word ends here.
insert(root, "cat") ch = 'c' not in node.kids -> new Node() (line 5), step down (line 6) ch = 'a' not in node.kids -> new Node() (line 5), step down (line 6) ch = 't' not in node.kids -> new Node() (line 5), step down (line 6) node "cat": end = True (line 7) new nodes: 3, nodes below the root: 3Insert car: share the prefix
insert "car": 'c' and 'a' already exist, so line 6 just steps down them. Only 'r' is new. Words that start the same share one path, so the prefix "ca" is stored once.
insert(root, "car") ch = 'c' already there -> step down (line 6) ch = 'a' already there -> step down (line 6) ch = 'r' not in node.kids -> new Node() (line 5), step down (line 6) node "car": end = True (line 7) new nodes: 1, nodes below the root: 4Insert cart: car stays a word
insert "cart": c, a and r all exist; only 't' is new, under "car". The "car" node keeps its gold dot, so both words are stored. An end flag can sit in the middle of a path.
insert(root, "cart") ch = 'c' already there -> step down (line 6) ch = 'a' already there -> step down (line 6) ch = 'r' already there -> step down (line 6) ch = 't' not in node.kids -> new Node() (line 5), step down (line 6) node "cart": end = True (line 7) new nodes: 1, nodes below the root: 5Insert dog: a new branch
insert "dog": the root has no 'd' child, so a second branch starts at the root: lines 5 and 6 for each letter, line 7 at the end. Four words, 13 letters in total, but only 8 nodes below the root: shared prefixes saved 5.
insert(root, "dog") ch = 'd' not in node.kids -> new Node() (line 5), step down (line 6) ch = 'o' not in node.kids -> new Node() (line 5), step down (line 6) ch = 'g' not in node.kids -> new Node() (line 5), step down (line 6) node "dog": end = True (line 7) new nodes: 3, nodes below the root: 8 (root) c a t end r end t end d o g endFind cart: one hop per letter
find(root, "cart") follows one link per letter (line 14): c, a, r, t. 4 hops, and the node it lands on has end = True, so "cart" is stored. The "dog" branch is never looked at.
find(root, "cart") ch = 'c' in node.kids -> node = "c" (line 14) ch = 'a' in node.kids -> node = "ca" (line 14) ch = 'r' in node.kids -> node = "car" (line 14) ch = 't' in node.kids -> node = "cart" (line 14) return node "cart" (line 15) search: node is not None and node.end -> TrueFind cap: a miss stops early
find "cap": c and a are there, but the "ca" node has no 'p' child. Line 13 returns None after checking 3 letters. A miss can stop sooner, even at the first letter.
find(root, "cap") ch = 'c' in node.kids -> node = "c" ch = 'a' in node.kids -> node = "ca" ch = 'p' not in node.kids (line 12) return None (line 13) node "ca" has kids: 't', 'r'Find ca: only a prefix
find "ca" does reach a node, but its end flag is False: "ca" is the start of stored words, not a word itself. So a word search needs both: the node exists and its end is True.
find(root, "ca") -> node "ca" (line 15) node "ca".end = False def search(root, word): node = find(root, word) return node is not None and node.end search(root, "ca") -> False search(root, "car") -> TrueEvery word that starts with ca
Words starting with "ca": walk to the "ca" node, then visit everything below it. Each gold dot is a word: car, cart, cat. Visiting kids in sorted letter order lists them alphabetically. Autocomplete works this way.
def words_under(node, prefix): if node.end: yield prefix for ch in sorted(node.kids): yield from words_under(node.kids[ch], prefix + ch) list(words_under(find(root, "ca"), "ca")) -> ['car', 'cart', 'cat']Cost: the length, not the count
Line 11 loops once per letter: O(L) for a string of length L, however many words are stored. A balanced search tree of n strings needs about log₂ n comparisons instead, and each one may read up to L letters.
trie: one dict lookup per letter (line 11 loops L times) find a string of length L: at most L steps a miss can stop at the first letter balanced BST of n strings: height about log2 n, each comparison reads up to L letters n = 1,000,000 words: about 20 comparisons price: one node per new letter, a dict in every node
5 quick questions
Choose one answer per question. You can change your choices before checking them.
01A trie holds cat, car and cart. How many new nodes does insert(root, "cars") create?
c, a and r already exist (they spell car), so the loop only steps down them. The only missing letter is the final s, so exactly one node is created, and line 7 sets its end flag.
02After inserting cat, car, cart and dog, find(root, "ca") returns a node. Why is "ca" still not a stored word?
A node only says a path exists. A word is stored only where an insert ended and set end = True. That is why search() checks both: the node is not None and node.end.
03How many letters does find(root, "cap") check before it returns None in that trie?
It checks c (there), a (there) and p, which is not in the kids of the "ca" node, so line 13 returns None after 3 checks. A miss stops at the first missing letter.
04The trie stores n words. What does finding one string of length L cost?
The walk follows one link per letter and never looks at other branches, so the work grows with L, not with n. A balanced BST of strings needs about log₂ n comparisons, each of which may read up to L letters.
05Why does words_under use sorted(node.kids) instead of plain node.kids?
Dicts remember the order keys were added: 't' went into the "ca" node before 'r'. Visiting the letters in sorted order lists the words alphabetically: car, cart, cat.
Glossary
- Trie
- A tree for strings with one letter per level. The name comes from retrieval; it is also called a prefix tree.
- Prefix
- The start of a string. "ca" is a prefix of car, cart and cat. Every trie node stands for one prefix.
- Root
- The top node of the trie. It stands for the empty string, the prefix of every word.
- kids
- In this lesson's code, a dict on each node that maps a letter to the child node for that letter.
- End flag
- A True/False field on a node, set when an inserted word ends there. Drawn as a gold dot in the figure.
- Search hit / miss
- A hit finds the node and its end flag is True. A miss runs into a missing letter, or stops on a node whose flag is False.
- Autocomplete
- Listing every stored word that starts with what was typed: walk to the prefix node, then visit everything below it.
- Radix tree
- A compressed trie that merges chains of single-child nodes into one link, to save space.
Notes and sources
- Here each node's kids is a Python dict, so checking one letter is an expected O(1) lookup. Sedgewick and Wayne's R-way trie uses an array of R links per node instead (R = 256 for extended ASCII): faster to index, but most links are empty.
- Sedgewick and Wayne: a search hit must examine all L characters, while a search miss can stop at the first mismatch. A balanced BST does O(log n) comparisons (MIT 6.006: operations are O(h) and h should be O(lg n)), and comparing two strings can read up to L characters.
- Python dicts keep insertion order, not alphabetical order (the "ca" node got 't' before 'r'), so words_under sorts the letters. CLRS (3rd ed., Problem 12-2) uses the same idea to sort strings of total length n in Θ(n) time (CLRS calls its plain binary trie over bit strings a "radix tree", unlike the compressed tree in the glossary).
- The name comes from retrieval. Real libraries often compress chains of single-child nodes into one edge (a radix tree or compressed trie) to save space.
- Sedgewick and Wayne, Algorithms 4th ed., §5.2 Tries
- Sedgewick and Wayne, lecture slides 5.2 Tries (trie performance, ordered iteration, prefix matches)
- MIT 6.006 Introduction to Algorithms (Fall 2011), Lecture 5: Binary search trees
- Cormen, Leiserson, Rivest and Stein, Introduction to Algorithms, 3rd ed. (MIT Press, 2009), Problem 12-2: Radix trees
- Python Library Reference: Mapping types, dict
- Trie (overview and history)
Quiz Unlocks after the last step.