How a trie stores keys on a path from the root

Short answer: A trie stores a set of strings so that each edge is a character and each root-to-node path is a prefix. Lookup of a string of length L examines O(L) edges, independent of how many other keys exist. A node that ends a key is marked terminal. The plain trie spends memory on a child array per node. A radix tree, or Patricia trie, compresses chains of single-child nodes into one edge labeled with several characters.


What the problem actually asks

A balanced search tree compares whole keys and takes O(L log n) character work in the worst case when each comparison scans the string. A trie compares each character once, against the edge that leaves the current node. The set of keys that share a prefix share the path, so the structure is also the right index for autocomplete and for longest-prefix match.

The cost moves to memory. An alphabet of size σ and a pointer per symbol at every node is sparse when most nodes have one child. Compression of those chains does not change which strings are stored. It changes how many nodes a walk touches.


What the algorithm guarantees

Insert, delete, and exact lookup are O(L) character steps. Enumerating every key with a given prefix is a walk of that subtree, linear in the size of the output plus the prefix. Extra memory for an array trie is O(N · σ) in the worst case, where N is the number of nodes, and much less with a hash map or a sorted list of children at each node. A radix tree uses O(n) nodes for n keys after compression, up to constants.

The trie does not keep a balanced height in terms of n. A set of keys that are prefixes of one long string is already a path of length L, and that is optimal in the character model. Longest-prefix match, as in a routing table, returns the deepest terminal node on the walk. Aho-Corasick adds failure links to a trie of patterns so a text can be scanned once.


The working steps

  1. Start at the root. For each character of the key, follow the child edge labeled with that character. Create it on insert if it is missing.
  2. After the last character, set the terminal mark on insert, or report whether the mark is set on lookup.
  3. Delete clears the terminal mark. If the node has no children and is not the root, unlink it and walk back while the parent is a nonterminal with no remaining children.
  4. A longest-prefix query remembers the last terminal node seen during the walk and returns that prefix when a character misses.
  5. A radix compression merges a node that has a single child and is not terminal into the edge label below it. Splits reverse the merge when an insert diverges in the middle of a label.

The O(L) bound counts character steps, not comparisons of a total order. A hash table of whole strings is expected O(L) as well and does not answer prefix queries. A ternary search tree is another character tree, with a different node layout. Failure links for multiple-pattern search belong to Aho-Corasick, which starts from this trie.


Approaches that look simpler and fail

Approach Why it fails when a prefix is reported as a stored key
Return success when the walk consumes the query, with no terminal mark The query is a prefix of some key, or a path created by a longer key. Only the terminal mark means the string was inserted.
Allocate a child array of size σ and ignore the empty entries in the memory bound The empty slots are the memory. A map of present children is the compact alternative.
Delete a key by unlinking the leaf and stopping A longer key that extended past that node must stay. Clear the mark first, and unlink only nodes that no remaining key needs.
Expect log n height on adversarial strings Shared structure depends on the strings. One long chain of unique characters is a path, and the lookup is still O(L).

Whole-key equality with no prefix queries belongs to a hash table. Ordered predecessor queries belong to a balanced search tree or a radix tree with an in-order walk. Multiple patterns scanned in one text belong to Aho-Corasick.


A working example

This Python fragment stores keys on a path from the root. A terminal mark distinguishes a stored key from a prefix of another key. It prints yes no yes: cat is stored, ca is only a prefix, car is stored.

class Trie:
    def __init__(self):
        self.root = {}

    def insert(self, word):
        node = self.root
        for ch in word:
            node = node.setdefault(ch, {})
        node["$"] = True

    def search(self, word):
        node = self.root
        for ch in word:
            if ch not in node:
                return False
            node = node[ch]
        return "$" in node

t = Trie()
t.insert("cat")
t.insert("car")
print("yes" if t.search("cat") else "no", "yes" if t.search("ca") else "no", "yes" if t.search("car") else "no")

Where it is used

The Linux forwarding trie (fib_trie) looks up the longest matching IP prefix. Autocomplete dictionaries and radix trees for strings are the same path-from-the-root layout. A hash table finds an exact key and does not walk prefixes.


When you can drop this algorithm

Drop a trie when the keys are arbitrary comparable objects rather than sequences, or when the set is small and a hash table fits. Keep it for dictionaries, routing prefixes, and autocomplete, and compress single-child chains when the alphabet arrays dominate memory.


Why this stays published

We publish this so a search for a trie returns the terminal mark and the O(L) walk that does not depend on the size of the set. A trie stores each key as a path of characters from the root, answers lookup in time proportional to the key length, and uses a terminal mark to tell a stored key from a proper prefix.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *