Sub topic 2
Anatomy of a trie node
This chapter assumes you know Python dictionaries, how a tree is built from linked nodes, and basic Big-O notation. Here you will look at the one building block a trie is made of, the node. Insert and search come in the next chapters.
What a node represents
A trie stores strings one character at a time. In a trie, a node does not hold a character. A node stands for a prefix: the string you get by reading the characters on the path from the root down to that node. The character itself is stored on the link from a parent to a child, as a key in the parent's children dictionary.
The root stands for the empty prefix "". It never holds a character, and every word starts from it.
The two fields
A basic node needs only two fields.
| Field | Type | Purpose |
|---|---|---|
| `children` | dict mapping a character to a `TrieNode` | The outgoing links. Each key is the next character of a longer prefix. |
| `is_end` | bool | `True` if the prefix at this node is a complete word that was inserted. |
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = FalseThe Trie class wraps a single root node:
class Trie:
def __init__(self):
self.root = TrieNode()Why the end marker is needed
Suppose you store car, card and cat. The path c → a → r exists because card passes through it. Without more information, you could not tell whether car is a stored word or only the beginning of card.
The is_end flag settles this. The node for car has is_end = True, while the node for ca has is_end = False. The shape of the tree says which prefixes exist. The flag says which of those prefixes are words.
Note that car is both a word and the parent of another node. A node can be an end of a word and still have children.
Building a path by hand
You can see the structure by linking nodes without any insert method. This code builds the single word car and then inspects it:
class TrieNode:
def __init__(self):
self.children = {}
self.is_end = False
root = TrieNode()
node = root
for ch in "car":
node.children[ch] = TrieNode()
node = node.children[ch]
node.is_end = True
# Follow the path c -> a and look at that node
ca = root.children["c"].children["a"]
print(list(ca.children)) # ['r']
print(ca.is_end) # False: "ca" is only a prefix
car = ca.children["r"]
print(car.is_end) # True: "car" is a stored word
print(car.children) # {}: nothing continues past "car"A node with an empty children dictionary is a leaf. In a trie where every word was inserted normally, every leaf has is_end = True. Later, deletion will rely on this fact.
Common mistakes
- Sharing one dictionary between nodes. Writing
children = {}as a class attribute, or as a default argument such asdef __init__(self, children={}), gives every node the same dictionary. Inserting a word anywhere then appears to add it everywhere. Create the dictionary inside__init__, as above. - Storing the character in the node. A
charfield duplicates the key in the parent's dictionary and gets out of sync easily. The root has no character at all, so the field would also need a special case. - Forgetting the end marker. If you skip
is_end, a search forcasucceeds after inserting onlycar. - Treating
is_endas "has no children".caris a word and has a child. Leaf status and word status are separate facts.
Exercise
A trie contains only the words "to", "tea" and "ten". How many nodes does it have, counting the root, and which of them have is_end set to True?
Show answer
It has 6 nodes: the root, "t", "to", "te", "tea" and "ten". The nodes with is_end set to True are "to", "tea" and "ten". The nodes "t" and "te" are only prefixes, and the root stands for the empty prefix, so none of those three is an end.