# 字典树

字典树（trie，又称前缀树或数字树）是一种用于存储字符串的树形数据结构：每条边携带一个字符，因此每个节点代表从根节点出发的路径所拼出的前缀，存储的键的每一个不同前缀都恰好对应一个节点。<sup>[1](https://xlinux.nist.gov/dads/HTML/trie.html)</sup><sup> • </sup><sup>[2](https://prism.nicofortuin.com/algorithms/trie/)</sup> 一个字符串被存入字典树，当且仅当从根节点出发存在它的路径，且该路径终止于一个被标记为完整键的节点。<sup>[2](https://prism.nicofortuin.com/algorithms/trie/)</sup> 这个名字由[爱德华·弗雷德金](https://www.edgepedia.org/zh/edward-fredkin)（Edward Fredkin）创造，取自 *retrieval* 一词的中间音节；弗雷德金在 2008 年表示，他本意是把它读作“tree”，既指涉树形结构，又点明数据存储与检索的用途，不过“try”也是一种常见的读法。<sup>[1](https://xlinux.nist.gov/dads/HTML/trie.html)</sup>

| 关键事实 | 细节 |
|---|---|
| 结构 | 每个不同前缀一个节点；边以字符为标签；当且仅当键的路径存在且终止于被标记的节点时，该键存在<sup>[1](https://xlinux.nist.gov/dads/HTML/trie.html)</sup><sup> • </sup><sup>[2](https://prism.nicofortuin.com/algorithms/trie/)</sup> |
| 单点查找与插入 | O(L)，键的每个字符触碰一个节点；字典规模 n 从不进入单次查询时间<sup>[2](https://prism.nicofortuin.com/algorithms/trie/)</sup> |
| 前缀查询 | 到达前缀节点需 O(L)，随后枚举其下所有键的工作量与输出规模成正比；哈希表不能直接支持这一操作<sup>[2](https://prism.nicofortuin.com/algorithms/trie/)</sup><sup> • </sup><sup>[3](https://academia.sh/en/courses/data-structures/tries)</sup> |
| 有序遍历 | 按顺序走子边的深度优先遍历即可免费得到按字母序排列的键<sup>[2](https://prism.nicofortuin.com/algorithms/trie/)</sup> |
| 内存 | 主要代价：最坏情况下节点数为 O(总字符数)，每个节点带一张子节点表；R 路数组节点每节点耗费 R 个指针<sup>[2](https://prism.nicofortuin.com/algorithms/trie/)</sup><sup> • </sup><sup>[4](https://dsa.handbook.academy/curriculum/trees-heaps/tries/)</sup> |
| 压缩形式 | 基数树/PATRICIA 树把单子节点链合并为多字符边；Linux 内核的 IP 路由表使用压缩字典树<sup>[4](https://dsa.handbook.academy/curriculum/trees-heaps/tries/)</sup><sup> • </sup><sup>[5](https://cdn.kernel.org/doc/html/latest/networking/fib_trie.html)</sup> |
| 起源 | 勒内·德·拉·布里安代，《使用变长键进行文件搜索》（1959）；爱德华·弗雷德金，《字典树内存》，《ACM 通讯》3(9):490–499，1960 年 9 月<sup>[1](https://xlinux.nist.gov/dads/HTML/trie.html)</sup> |

## 基本操作

插入时沿已有的前缀节点下行，只为尚不存在的前缀创建节点，并在完整单词对应的节点上设置键结束标记。查找走同样的路径并检查该标记。删除则更微妙：先清除节点的标记，然后只在节点既无标记又无子节点时向上剪枝，一旦遇到其他键共享的节点便停止。<sup>[2](https://prism.nicofortuin.com/algorithms/trie/)</sup>

由于每次操作对输入的每个字符触碰一个节点，运行时间取决于键的长度，而非已存储键的数量。查找失败可能格外快：不匹配也许在第一个字符就发生，因此典型的未命中只需检查少数几个字符。<sup>[6](https://www.cs.princeton.edu/courses/archive/fall11/cos226/lectures/52Tries.pdf)</sup> 分支因子影响每条边的代价（数组查找为常数，哈希子节点映射为期望常数），但不影响路径长度。<sup>[4](https://dsa.handbook.academy/curriculum/trees-heaps/tries/)</sup>

字典树还是一种无需额外工作即有序的结构：按字典序迭代就是一次按字母顺序走子边的深度优先遍历，这是哈希映射做不到的。<sup>[2](https://prism.nicofortuin.com/algorithms/trie/)</sup>

## 节点表示与内存

内存是字典树实打实的代价。最坏情况下，若前缀毫无共享，结构中的节点数等于所存字符总数，每个节点带一张子节点表。<sup>[2](https://prism.nicofortuin.com/algorithms/trie/)</sup> 经典的 R 路数组表示每次下行只需一次带索引的解引用，并在连续的 R 个槽位上获得完整的缓存局部性，但无论节点只有一个子节点还是有 R 个，都要付出 R 个指针的代价；塞奇威克与韦恩（Sedgewick and Wayne）的分析认为，R 路字典树的空间为 (R + 1)N 个引用，并称其是小字母表下的首选方法，但对大字母表而言过于耗内存，例如 Unicode 的 65,536 路字典树。<sup>[4](https://dsa.handbook.academy/curriculum/trees-heaps/tries/)</sup><sup> • </sup><sup>[6](https://www.cs.princeton.edu/courses/archive/fall11/cos226/lectures/52Tries.pdf)</sup> 用哈希映射存子节点可把内存降到每节点 O(d<sub>v</sub>)，其中 d<sub>v</sub> 是实际用到的不同子字符数，代价是每条边一次哈希。<sup>[4](https://dsa.handbook.academy/curriculum/trees-heaps/tries/)</sup>

双数组字典树由 J. 青江（J. Aoe）于 1989 年提出，仅用 base 和 check 两个整数数组表示整棵字典树，每次访问节点为常数时间且无需指针；其空间可能增长到节点数乘以字母表大小，而坂内英夫（Hideo Bannai）、后藤启介（Keisuke Goto）、神田峻介（Shunsuke Kanda）与多米尼克·克普尔（Dominik Köppl）2024 年的结果证明：判定给定规模的双数组是否存在是 NP 完全的，即便字母表规模为对数级亦然。<sup>[7](https://arxiv.org/abs/2403.04951)</sup>

## 压缩变体

当键很长而共享前缀很少时，朴素字典树几乎全是分支、鲜有共享，压缩便成为必需。<sup>[8](https://mexicodev.org/en/dsa-course/tries/index.html)</sup>

**基数树与 PATRICIA 树。** 压缩字典树，即基数树，把任意一条单子节点链合并为一条以多字符字符串为标签的边，从而大幅削减节点数；这是路由表中实际使用的生产形态。<sup>[2](https://prism.nicofortuin.com/algorithms/trie/)</sup><sup> • </sup><sup>[4](https://dsa.handbook.academy/curriculum/trees-heaps/tries/)</sup> PATRICIA 算法由唐纳德·R·莫里森（Donald R. Morrison）于 1968 年发表在《ACM 杂志》上（该名取自“检索以字母数字编码的信息的实用算法”这一英文名称的首字母），它附加了一条约束：消除只有一个后代的节点；最初是为基于磁盘的文本检索而实现的。<sup>[9](https://explore.openaire.eu/search/publication?pid=10.1145%2F321479.321481)</sup>

**路由中的路径压缩与层级压缩。** Linux 内核的 IP 路由表建立在一棵压缩字典树之上，其实现说明描述了两种技术：路径压缩跳过那些代表无分叉单一路径的键的比特位；层级压缩自适应地调整每个内部节点子数组的大小，反复倍增或减半，直到满足最优层级压缩的判据。<sup>[5](https://cdn.kernel.org/doc/html/latest/networking/fib_trie.html)</sup> 查找时按键段逐段下行至叶节点，再向上回溯、逐段截去键的尾部，以找出最长匹配前缀。<sup>[5](https://cdn.kernel.org/doc/html/latest/networking/fib_trie.html)</sup>

**自适应基数树。** 自适应基数树（ART）由维克托·莱斯（Viktor Leis）及其同事在 ICDE 2013 上提出，面向主内存数据库索引。它自适应地选择紧凑的节点表示，以解决多数基数树最坏情况下空间消耗过大的问题；其查找性能超过高度调优的只读搜索树，速度可与哈希表相比，同时保持数据有序，从而支持哈希表不支持的区间扫描与前缀查找。<sup>[10](https://ieeexplore.ieee.org/document/6544812/)</sup> 据一项案例研究，把标准字典树换成自适应基数树后，内存消耗从 825 MB 降至 18 MB，查找速度还快了 4 倍。<sup>[11](https://github.com/djiangtw/data-structures-in-practice-public/blob/main/manuscript/chapters/chapter11.md)</sup>

**缓存友好的混合结构。** 尼古拉斯·阿斯基蒂斯（Nikolas Askitis）与兰詹·辛哈（Ranjan Sinha）的 HAT 字典树把字典树与类哈希表的桶结合起来以改善缓存行为；作者报告其在多数情况下性能接近缓存友好的哈希表，同时保持排序顺序。<sup>[12](https://citeseerx.ist.psu.edu/document?doi=cbd461aebf6c8288d7afddbb30f7b727d798044b&repid=rep1&type=pdf)</sup>

## 与哈希表和搜索树的比较

对于字符串键，三种标准结构的分工各不相同：<sup>[3](https://academia.sh/en/courses/data-structures/tries)</sup>

| 指标 | 字典树 | 哈希表 | 平衡搜索树 |
|---|---|---|---|
| 单点查找 | O(m) | 平均 O(m) | O(m log n) |
| 前缀查询 | 直接支持 | 不支持 | 部分支持，需借助区间查询 |
| 有序遍历 | 支持 | 不支持 | 支持 |
| 内存 | 高 | 中等 | 中等 |

字典树避免了平衡搜索树因搜索路径上每个节点都要比较字符串而产生的 log n 代价。<sup>[3](https://academia.sh/en/courses/data-structures/tries)</sup> 在纯粹的成员测试上，哈希集合通常在常数因子和内存上占优，以 O(L) 时间作答，空间远小于字典树的节点与子节点映射；字典树的用武之地是前缀操作，哈希表对此完全无能为力。<sup>[2](https://prism.nicofortuin.com/algorithms/trie/)</sup><sup> • </sup><sup>[8](https://mexicodev.org/en/dsa-course/tries/index.html)</sup> 字典树还能对不可能的前缀快速失败；除非使用子节点映射或压缩，否则它不适合大字母表。<sup>[8](https://mexicodev.org/en/dsa-course/tries/index.html)</sup>

## 应用

字典树特有的查询能力支撑着自动补全、拼写检查建议、IP 路由中的最长前缀匹配、T9 键盘以及文字游戏求解器。<sup>[2](https://prism.nicofortuin.com/algorithms/trie/)</sup> 在路由中，路由器选择前缀与目的地址匹配最长的那条路由表项，这是最长前缀查询而非精确匹配。<sup>[6](https://www.cs.princeton.edu/courses/archive/fall11/cos226/lectures/52Tries.pdf)</sup>

Aho-Corasick 算法从一组关键词构建有限状态模式匹配机，其核心结构就是字典树；构建时间与关键词长度之和成正比，处理文本时的状态转移次数与关键词数量无关，该算法曾使一个图书馆书目检索程序提速 5 至 10 倍。<sup>[13](https://bishtref.com/articles/10.1145/360825.360855)</sup> 双数组字典树在分词、模式匹配、语言模型和文本分类中充当紧凑、可序列化的词典。<sup>[7](https://arxiv.org/abs/2403.04951)</sup>

## References

1. [Paul E. Black, "trie", Dictionary of Algorithms and Data Structures, NIST, ed. 12 February 2019](https://xlinux.nist.gov/dads/HTML/trie.html)
2. [Trie — visualized, explained, Prism](https://prism.nicofortuin.com/algorithms/trie/)
3. [Tries — Data Structures, Academia.sh](https://academia.sh/en/courses/data-structures/tries)
4. [Tries — The DSA Handbook](https://dsa.handbook.academy/curriculum/trees-heaps/tries/)
5. [LC-trie implementation notes, The Linux Kernel documentation](https://cdn.kernel.org/doc/html/latest/networking/fib_trie.html)
6. [Robert Sedgewick and Kevin Wayne, Algorithms, 4th edition, section 5.2 lecture slides, Princeton COS 226](https://www.cs.princeton.edu/courses/archive/fall11/cos226/lectures/52Tries.pdf)
7. [Hideo Bannai, Keisuke Goto, Shunsuke Kanda, Dominik Köppl (2024). NP-Completeness for the Space-Optimality of Double-Array Tries. arXiv](https://arxiv.org/abs/2403.04951)
8. [Tries and prefix trees — Data Structures & Algorithms, From Scratch, MexicoDev](https://mexicodev.org/en/dsa-course/tries/index.html)
9. [Donald R. Morrison (1968). PATRICIA — Practical Algorithm To Retrieve Information Coded in Alphanumeric. Journal of the ACM 15:514–534](https://explore.openaire.eu/search/publication?pid=10.1145%2F321479.321481)
10. [Viktor Leis and colleagues (2013). The Adaptive Radix Tree: ARTful Indexing for Main-Memory Databases. ICDE 2013, IEEE](https://ieeexplore.ieee.org/document/6544812/)
11. [Data Structures in Practice, chapter 11: Tries (GitHub manuscript)](https://github.com/djiangtw/data-structures-in-practice-public/blob/main/manuscript/chapters/chapter11.md)
12. [Nikolas Askitis, Ranjan Sinha (2007). HAT-trie: A Cache-conscious Trie-based Data Structure for Strings](https://citeseerx.ist.psu.edu/document?doi=cbd461aebf6c8288d7afddbb30f7b727d798044b&repid=rep1&type=pdf)
13. [Alfred V. Aho, Margaret J. Corasick (1975). Efficient string matching. Communications of the ACM 18(6):333–340](https://bishtref.com/articles/10.1145/360825.360855)

---
*Initially written Sep 17, 2026 · Reviewed: Sep 30, 2026; Oct 15, 2026 · Edited: Sep 30, 2026; Oct 15, 2026 · Last review: Oct 15, 2026*

Topic: 技术与人造世界 › 计算技术与数字系统 › 人工智能与数据 › Algorithms and computational methods › Data structures › Trees

Copyright 2026 Edgepedia

License: Edgepedia Community License 1.0, https://www.edgepedia.org/edgepedia/license

Source: https://www.edgepedia.org/zh/trie

English original: https://www.edgepedia.org/trie
