Trie树(字典树)的介绍及Java实现

作者:小楼一夜听春雨 时间:2022-06-14 15:38:24 

简介

Trie树,又称为前缀树或字典树,是一种有序树,用于保存关联数组,其中的键通常是字符串。与二叉查找树不同,键不是直接保存在节点中,而是由节点在树中的位置决定。一个节点的所有子孙都有相同的前缀,也就是这个节点对应的字符串,而根节点对应空字符串。

它的主要特点如下:

根节点不包含字符,除根节点外的每一个节点都只包含一个字符。

从根节点到某一节点,路径上经过的字符连接起来,为该节点对应的字符串。

每个节点的所有子节点包含的字符都不相同。

如下是一棵典型的Trie树:

Trie树(字典树)的介绍及Java实现

Trie的来源是Retrieval,它常用于前缀匹配和词频统计。可能有人要说了,词频统计简单啊,一个hash或者一个堆就可以搞定,但问题来了,如果内存有限呢?还能这么 玩吗?所以这里我们就可以用trie树来压缩下空间,因为公共前缀都是用一个节点保存的。

1、定义

这里为了简化,只考虑了26个小写字母。

首先是节点的定义:


public class TrieNode {

public TrieNode[] children;

public char data;

public int freq;

public TrieNode() {
//因为有26个字母
children = new TrieNode[26];
freq = 0;
}

}

然后是Trie树的定义:


public class TrieTree {

private TrieNode root;

public TrieTree(){
root=new TrieNode();
}

...

}

2、插入

由于是26叉树,故可通过charArray[index]-‘a';来得知字符应该放在哪个孩子中。


public void insert(String word){
if(TextUtils.isEmpty(word)){
 return;
}
insertNode(root,word.toCharArray(),0);
}

private static void insertNode(TrieNode rootNode,char[]charArray,int index){

int k=charArray[index]-'a';
if(k<0||k>25){
 throw new RuntimeException("charArray[index] is not a alphabet!");
}
if(rootNode.children[k]==null){
 rootNode.children[k]=new TrieNode();
 rootNode.children[k].data=charArray[index];
}

if(index==charArray.length-1){
 rootNode.children[k].freq++;
 return;
}else{
 insertNode(rootNode.children[k],charArray,index+1);
}

}

3、移除节点

移除操作中,需要对词频进行减一操作。


public void remove(String word){
if(TextUtils.isEmpty(word)){
 return;
}
remove(root,word.toCharArray(),0);
}

private static void remove(TrieNode rootNode,char[]charArray,int index){
int k=charArray[index]-'a';
if(k<0||k>25){
 throw new RuntimeException("charArray[index] is not a alphabet!");
}
if(rootNode.children[k]==null){
 //it means we cannot find the word in this tree
 return;
}

if(index==charArray.length-1&&rootNode.children[k].freq >0){
 rootNode.children[k].freq--;
}

remove(rootNode.children[k],charArray,index+1);
}

4、查找频率


public int getFreq(String word){
if(TextUtils.isEmpty(word)){
 return 0;
}
return getFreq(root,word.toCharArray(),0);
}

private static int getFreq(TrieNode rootNode,char[]charArray,int index){
int k=charArray[index]-'a';
 if(k<0||k>25){
 throw new RuntimeException("charArray[index] is not a alphabet!");
}
//it means the word is not in the tree
if(rootNode.children[k]==null){
 return 0;
}
if(index==charArray.length-1){
 return rootNode.children[k].freq;
}
return getFreq(rootNode.children[k],charArray,index+1);
}

5、测试

测试代码如下:


public static void test(){
TrieTree trieTree=new TrieTree();
String sourceStr="Democratic presumptive nominee Hillary Clintons campaign posed pounced on Trumps assertion that British term monetary turmoil might benefit his business venture in Scotland";

//String sourceStr="the that";
sourceStr=sourceStr.toLowerCase();

String[]strArray=sourceStr.split(" ");
for(String str:strArray){
 trieTree.insert(str);
}

String sourceStr2="Every president is tested by world events But Donald Trump thinks about how is his golf resort can profit from that";
sourceStr2=sourceStr2.toLowerCase();
String[]strArray2=sourceStr2.split(" ");
for(String str:strArray2){
 trieTree.insert(str);
}

BinaryTree.print("frequence of 'that':"+trieTree.getFreq("that"));
BinaryTree.print("\nfrequence of 'donald':"+trieTree.getFreq("donald"));

trieTree.remove("that");
BinaryTree.print("\nafter remove 'that' once,freq of 'that':"+trieTree.getFreq("that"));
trieTree.remove("that");
BinaryTree.print("\nafter remove 'that' twice,freq of 'that':"+trieTree.getFreq("that"));

trieTree.remove("donald");
BinaryTree.print("\nafter remove 'donald' once,freq of 'donald':"+trieTree.getFreq("donald"));

BinaryTree.reallyStartPrint();

}

测试结果如下:

Trie树(字典树)的介绍及Java实现

总结

标签:java,trie树,字典树
0
投稿

猜你喜欢

  • IDEA基于支付宝小程序搭建springboot项目的详细步骤

    2021-10-30 22:44:46
  • C#面向对象设计的七大原则

    2021-10-21 04:15:49
  • IDEA实用好用插件推荐及使用方法教程详解(必看)

    2021-07-15 19:10:44
  • Java设计模式之享元模式

    2022-09-23 12:16:07
  • Mybatis 入门之MyBatis环境搭建(第一篇)

    2023-03-15 16:09:32
  • Java JDBC导致的反序列化攻击原理解析

    2023-09-24 15:38:42
  • 详解Java中NullPointerException异常的原因详解以及解决方法

    2023-01-22 20:13:28
  • 用Linq从一个集合选取几列得到一个新的集合(可改列名)

    2023-08-23 22:48:23
  • C# LINQ查询表达式及对应LAMBDA表达式的用法

    2023-07-31 19:15:26
  • Java List集合排序实现方法解析

    2023-01-06 05:40:14
  • SpringBoot2 参数管理实践之入参出参与校验的方式

    2022-12-25 02:44:30
  • IDEA利用自带Axis工具和wsdl文件反向生成服务端客户端代码图文详解

    2021-12-06 20:02:12
  • Java String转换时为null的解决方法

    2022-08-25 08:16:00
  • mybatis源码解读之executor包懒加载功能 

    2022-09-17 00:28:05
  • startActivityForResult和setResult案例详解

    2023-09-15 19:13:33
  • Java计算两个程序运行时间的实例

    2022-01-30 14:49:06
  • struts中动态方法调用使用通配符

    2023-02-01 02:52:43
  • 使用springboot整合RateLimiter限流过程

    2022-09-12 21:42:48
  • 通过实例解析Spring argNames属性

    2023-09-14 10:43:13
  • SpringBoot微信消息接口配置详解

    2023-08-23 09:51:21
  • asp之家 软件编程 m.aspxhome.com