{"id":129,"date":"2026-11-13T12:32:10","date_gmt":"2026-11-13T04:32:10","guid":{"rendered":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-a-trie-stores-keys-on-a-path-from-the-root\/"},"modified":"2026-11-13T21:50:56","modified_gmt":"2026-11-13T13:50:56","slug":"how-a-trie-stores-keys-on-a-path-from-the-root","status":"publish","type":"post","link":"https:\/\/hoho.live\/luda\/index.php\/2026\/11\/13\/how-a-trie-stores-keys-on-a-path-from-the-root\/","title":{"rendered":"How a trie stores keys on a path from the root"},"content":{"rendered":"\n<p class=\"wp-block-paragraph\"><strong>Short answer:<\/strong> A <strong>trie<\/strong> 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 <strong>O(L)<\/strong> 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 <strong>radix tree<\/strong>, or Patricia trie, compresses chains of single-child nodes into one edge labeled with several characters.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the problem actually asks<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<p class=\"wp-block-paragraph\">The cost moves to memory. An alphabet of size \u03c3 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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>What the algorithm guarantees<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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 \u00b7 \u03c3) 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.<\/p>\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>The working steps<\/strong><\/h4>\n\n<ol class=\"wp-block-list\">\n<li>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.<\/li>\n<li>After the last character, set the terminal mark on insert, or report whether the mark is set on lookup.<\/li>\n<li>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.<\/li>\n<li>A longest-prefix query remembers the last terminal node seen during the walk and returns that prefix when a character misses.<\/li>\n<li>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.<\/li>\n<\/ol>\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Approaches that look simpler and fail<\/strong><\/h4>\n\n<figure class=\"wp-block-table\">\n<table>\n<thead>\n<tr>\n<th>Approach<\/th>\n<th>Why it fails when a prefix is reported as a stored key<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr>\n<td>Return success when the walk consumes the query, with no terminal mark<\/td>\n<td>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.<\/td>\n<\/tr>\n<tr>\n<td>Allocate a child array of size \u03c3 and ignore the empty entries in the memory bound<\/td>\n<td>The empty slots are the memory. A map of present children is the compact alternative.<\/td>\n<\/tr>\n<tr>\n<td>Delete a key by unlinking the leaf and stopping<\/td>\n<td>A longer key that extended past that node must stay. Clear the mark first, and unlink only nodes that no remaining key needs.<\/td>\n<\/tr>\n<tr>\n<td>Expect log n height on adversarial strings<\/td>\n<td>Shared structure depends on the strings. One long chain of unique characters is a path, and the lookup is still O(L).<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/figure>\n\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>A working example<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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 <code>yes no yes<\/code>: <code>cat<\/code> is stored, <code>ca<\/code> is only a prefix, <code>car<\/code> is stored.<\/p>\n\n<pre><code class=\"language-python\">class Trie:\n    def __init__(self):\n        self.root = {}\n\n    def insert(self, word):\n        node = self.root\n        for ch in word:\n            node = node.setdefault(ch, {})\n        node[&quot;$&quot;] = True\n\n    def search(self, word):\n        node = self.root\n        for ch in word:\n            if ch not in node:\n                return False\n            node = node[ch]\n        return &quot;$&quot; in node\n\nt = Trie()\nt.insert(&quot;cat&quot;)\nt.insert(&quot;car&quot;)\nprint(&quot;yes&quot; if t.search(&quot;cat&quot;) else &quot;no&quot;, &quot;yes&quot; if t.search(&quot;ca&quot;) else &quot;no&quot;, &quot;yes&quot; if t.search(&quot;car&quot;) else &quot;no&quot;)\n<\/code><\/pre>\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Where it is used<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">The <strong>Linux forwarding trie<\/strong> (<code>fib_trie<\/code>) 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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>When you can drop this algorithm<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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.<\/p>\n\n\n<hr class=\"wp-block-separator has-alpha-channel-opacity\"\/>\n\n<h4 class=\"wp-block-heading\"><strong>Why this stays published<\/strong><\/h4>\n\n<p class=\"wp-block-paragraph\">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. <strong>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.<\/strong><\/p>\n\n\n<p class=\"wp-block-paragraph\">\u672c\u6587\u7531 HoHo \u8207 AI \u5354\u4f5c\u6574\u7406\uff0c\u6700\u5f8c\u66f4\u65b0\u65bc 2026 \u5e74 11 \u6708 13 \u65e5\u3002<\/p>\n","protected":false},"excerpt":{"rendered":"<p>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.&hellip;<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[30,34],"tags":[],"class_list":["post-129","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-trees"],"_links":{"self":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/129","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/comments?post=129"}],"version-history":[{"count":2,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/129\/revisions"}],"predecessor-version":[{"id":528,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/posts\/129\/revisions\/528"}],"wp:attachment":[{"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/media?parent=129"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/categories?post=129"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/hoho.live\/luda\/index.php\/wp-json\/wp\/v2\/tags?post=129"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}