Trie树,又称为单词查找树,字典树,键树。是哈希树的变种。
应用与统计和排序大量字符串,所以经常用于搜索引擎系统用于文本词频系统。
优点:最大限度的减少无谓的字符串的比较,查找效率比哈希表高。
基本性质:
1)根节点不包含字符,除根外每个节点只包含一个字符。
2)从根节点到某一节点,路径上经过的字符连起来,为该结点对应的字符串。
3)每个结点包含的所有子结点都不相同。
应用与统计和排序大量字符串,所以经常用于搜索引擎系统用于文本词频系统。
优点:最大限度的减少无谓的字符串的比较,查找效率比哈希表高。
基本性质:
1)根节点不包含字符,除根外每个节点只包含一个字符。
2)从根节点到某一节点,路径上经过的字符连起来,为该结点对应的字符串。
3)每个结点包含的所有子结点都不相同。
注:设置标志,表示该字符是否为结束字符。不一定是最后字符。例如does,其中do中的o就有标志。
本片中给出TrieTree树的结构定义和插入,查询,删除操作。
一、Trie树的结构定义
import java.util.LinkedList;
/**
* trietree的结点定义形式
* */
public class TrieTreeNode {
char content;//节点中包含的字符
boolean isEnd;//是否为单词的最后一个字符
int count;//包含这个字符的单词个数
LinkedList<TrieTreeNode> childList;//子结点序列
//初始化
public TrieTreeNode(char c){
childList = new LinkedList<TrieTreeNode>();
isEnd = false;
content = c;
count = 0;
}
//trietree中是否包含字符c结点,包含则返回该字符,否则返回空
public TrieTreeNode subNode(char c){
if(childList != null){
for (TrieTreeNode trieTreeNode : childList) {
if(trieTreeNode.content == c){
return trieTreeNode;
}
}
}
return null;
}
}
二、Trie树的插入,查找和删除结点的方法
public class TrieTree {
public static void main(String[] args) {
//测试代码
TrieTree trie = new TrieTree();
trie.insert("zengxiao");
trie.insert("zengxiaoqiang");
trie.insert("haohaoxuexi");
System.out.println(trie.search("zengxiao"));
System.out.println(trie.search("zeng"));
trie.delete("zengxiao");
System.out.println(trie.search("zengxiao"));
}
private TrieTreeNode root;
public TrieTree(){
root = new TrieTreeNode(' ');
}
/**
* 将字符串的字符插入到trietree中
* @param word
*/
public void insert(String word){
if(search(word) == true){
return;
}
TrieTreeNode current = root;
for(int i=0; i<word.length(); i++){
TrieTreeNode child = current.subNode(word.charAt(i));//生成一个结点
if(child != null){
current = child;
}else{
current.childList.add(new TrieTreeNode(word.charAt(i)));
current = current.subNode(word.charAt(i));
}
current.count++;
}
current.isEnd = true;
}
/**
* 查找字符串是否在trietree中
* @param word
* @return
*/
public boolean search(String word){
TrieTreeNode current = root;
for(int i=0; i<word.length(); i++){
if(current.subNode(word.charAt(i)) == null){
return false;
}else{
current = current.subNode(word.charAt(i));
}
}
if(current.isEnd == true){
return true;
}else{
return false;
}
}
public void delete(String word){
if(search(word) == false){//没有找到字符串word则不用做任何操作
return ;
}
TrieTreeNode current = root;
for (char c : word.toCharArray()) {
TrieTreeNode child = current.subNode(c);
if(child.count == 1){
current.childList.remove(child);
return;
}else{
child.count--;
current = child;
}
}
current.isEnd = false;
}
}