p?rootcatrtdog1def insert(root, word):2 node = root3 for ch in word:4 if ch not in node.kids:5 node.kids[ch] = Node()6 node = node.kids[ch]7 node.end = True89def find(root, s):10 node = root11 for ch in s:12 if ch not in node.kids:13 return None14 node = node.kids[ch]15 return nodes[0]s[1]s[2]s[3]
Node blocks: one prefix each, labelled with its last letter; a gold dot = a word ends hereRow: the letters of the string being inserted or looked upToken: the letter the walk is looking for, one level per letterA trie on a board: every node is a prefix, the root is the empty string, and the letter on a node is the one that leads to it from its parent. A gold dot marks a node where a stored word ends. Inserting a word walks one level per letter and adds a node only where the letter is missing, so cat, car and cart share the path c, a. A find also takes one hop per letter; everything below a node is every word with that prefix.

Building a trie

  1. 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.

Looking words up

Prefixes and cost

What happens

;; step 1/10 · trie-idea
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"

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.