在计算机科学中,trie,又称前缀树或字典树,是一种有序树,用于保存关联数组,其中的键通常是字符串。与二叉查找树不同,键不是直接保存在节点中,而是由节点在树中的位置决定。一个节点的所有子孙都有相同的前缀,也就是这个节点对应的字符串,而根节点对应空字符串。一般情况下,不是所有的节点都有对应的值,只有叶子节点和部分内部节点所对应的键才有相关的值。
Trie这个术语来自于retrie
val。
Trie节点的定义:
public class TrieNode {
boolean isEnd;
// next数组的长度是26
TrieNode[] next;
public TrieNode() {
isEnd = false;
next = new TrieNode[26];
}
}
主要的函数签名:
/** 插入一个单词到trie中 */
public void insert(String word);
/**检查单词word是否在 trie 中 */
public boolean search(String word);
/** 检查trie树中的单词是否存在以prefix开头的 */
public boolean startsWith(String prefix);
方法实现如下:
class Trie {
// 用空间换时间的典型
// 建树所用的空间比较大
// 但是查询快。假设要查找的字符串word的长度为n,那么最多只需要查询n次就可以知道其是否存在
class TrieNode {
boolean isEnd;
// next数组的长度是26
TrieNode[] next;
public TrieNode() {
isEnd = false;
next = new TrieNode[26];
}
}
private TrieNode root;
/** Initialize your data structure here. */
public Trie() {
root = new TrieNode();
}
/** Inserts a word into the trie. */
public void insert(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
if (node.next[c - 'a'] == null) {
node.next[c - 'a'] = new TrieNode();
}
node = node.next[c - 'a'];
}
node.isEnd = true;
}
/** Returns if the word is in the trie. */
public boolean search(String word) {
TrieNode node = root;
for (char c : word.toCharArray()) {
node = node.next[c - 'a'];
if (node == null) {
return false;
}
}
return node.isEnd;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
public boolean startsWith(String prefix) {
TrieNode node = root;
for (char c : prefix.toCharArray()) {
node = node.next[c - 'a'];
if (node == null) {
return false;
}
}
return true;
}
}