前缀树又叫单词查找树/字典树,Tire树,是哈希树的变种。典型应用于统计,排序和保存大量字符串,经常被搜索引擎系统用于文本词频统计。
前缀树的每一个节点会有多个子节点,通往不同子节点的路径上有着不同的字符串(不仅限于字符串)。
优点:可以利用字符串的公共前缀来减少查询时间,最大限度地减少不必要的字符串比较,查询效率比哈希树高。
前缀树每个节点都有一个子节点数组用于保存路径,当问题需要解决在一个集合中查找是否存在另一个集合的元素前缀时,考虑使用前缀树。
实现(leetcode版)
class Trie {
private Trie[] children;
private boolean isEnd;
public Trie() {
children = new Trie[26];
isEnd = false;
}
public void insert(String word) {
Trie node = this;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);
int index = ch - 'a';
if (node.children[index] == null) {
nod