前缀树是一种非典的的多叉树,多叉树好理解就是多个分支,非典型则是指前缀树的节点的数据结构与一般的树不同。
先上代码,再讲我的理解(对应于LeetCode 208)
class Trie {
private Node root;
public Trie() {
root = new Node();
}
public void insert(String word) {
Node tmp = root;
int pos = -1;
for (char ch : word.toCharArray()){
pos = ch - 'a'; //计算位置
if (tmp.next[pos] == null){ //如果该字母不存在
tmp.next[pos] = new Node();//则添加
}
tmp = tmp.next[pos];
}
tmp.isEnd = true;//别忘了,一个单词结束要标记为true
}
public boolean search(String word) {
Node tmp = root;
int pos = -1;
for (char ch : word.toCharArray()){
pos = ch - 'a';
if (tmp.next[pos] == null)
return false;
tmp = tmp.next[pos];
}
return tmp.isEnd;//判断是否是一个完整的单词
}
public boolean startsWith(String prefix) {
Node tmp = root;
int pos = -1;
for (char ch : prefix.toCharArray()){
pos = ch - 'a';
if (tmp.next[pos] == null)
return false;
tmp = tmp.next[pos];
}
return true;//与search的区别,只要能匹配上即可,无需关注是否为一个单词
}
}
class Node{
//为了简便处理,属性就设置为public了
public boolean isEnd;
public Node[] next;
public Node(){
isEnd = false;
next = new Node[26];
}
}
首先,观察一下字典树中Node的数据结构
class Node{
//为了简便处理,属性就设置为public了
public boolean isEnd;
public Node[] next;
public Node(){
isEnd = false;
next = new Node[26];
}
}
再看看一般多叉树的数据结构
class Node{
int value; //节点值
Node[] next; //所有孩子节点
public Node(){}
}
- 多叉树的节点保存的是当前节点的值以及其指向其所有孩子节点指针
- 字典树的节点保存的当前节点是否为某个单词的最后一个字母;理解字典树最重要的一点就是理解next数组,Node[] next = new Node[26], 数组下标对应于下一个字母是什么,例如,'a’对应于next[0],'b’对应于next[1]…依次类推,也就是说在字典树中用位置表示值