首页 > 编程知识 正文

java定义树结构,前缀树的应用

时间:2023-05-04 17:05:03 阅读:186821 作者:1881

前缀树Trie Trie也称为前缀树或字典树,用于确定字符串是否存在或具有字符串前缀。

包含八个密钥的树结构: a、to、tea、ted、ten、I、in、and “inn”。

在计算机科学中,trie也称为前缀树字典树,是用于存储关联数组的规则树,其中密钥是与双击树不同,密钥由节点在树中的位置决定,而不是直接存储在节点中。 节点的所有后代都具有相同的前缀,即对应于节点的字符串,而根节点对应于空字符串。 一般来说,并不是所有节点都有对应的值,只有叶节点和部分内部节点对应的密钥具有关联的值。 (来源: wiki )

树的优缺点

Trie树的中心思想是在空间上改变时间,利用字符串的公共前缀减少无用的字符串比较,提高查询的效率。

优点

插入和查询很有效率,而且都是o(m ) o(m ) )。 其中mm是要插入/查询的字符串的长度。

对于查询,有人会说,散列调度的复杂性是o(1) o(1)1)更快。 但是,qsdhh搜索的效率通常取决于哈希函数的好坏,如果不良的哈希函数引起了很多冲突,效率并不一定高于Trie树。

树中的不同关键字不冲突。

仅当一个关键字可以与多个值相关联时,树才会像hash冲突一样发生。

Trie树不需要求出hash值,对短字符串更快。 通常,需要遍历字符串才能获得hash值。

树可以按词典顺序对关键字进行排序。

缺点

如果散列函数好,则树的搜索效率低于qsdhh搜索。

空间消耗比较大。

实现前缀树代码

class trie {/* * initializeyourdatastructurehere.*//buildnodeclassprivateclassnode { node [ ] childs=new node [ 26 ]。 布尔士; //initalizerootnodeprivatenoderoot=new node (; public trie ()/* * insertsawordintothetrie.*/public void insert (string word ) ) insert (word,root ); }privatevoidinsert(stringword,Node node ) if ) node==null ) return; if(word.length(==0) ) { node.isLeaf=true; 返回; } intindex=index for char (word.charat (0) ); if(node.childs[index]==null ) { node.childs[index]=new Node; }insert(word.substring(1),node.childs[index] ); }/* * returnsifthewordisinthetrie.*/publicbooleansearch (string word ) return search (word,root ); } privatebooleansearch (string word,node ) if ) node==null ) return false; if(word.length(==0) return node.isLeaf; intindex=index for char (word.charat (0) ); returnsearch(word.substring(1),node.childs[index]; }/* * returnsifthereisanywordinthetriethatstartswithegivenprefix.*/publicbooleanstartswith { string prefix } { return sthethethetthettthethed } prefix.length (==0) return true; intindex=index for char (prefix.charat (0) ); if(node.childs[index]==null )返回假; return starts with (prefix.substring (1),node.childs[index]; //getcharindexprivateintindexforchar (charc ) ) { return c-'a ); }/* * * yourtrieobjectwillbeinstantiatedandcalledassuch : * trie obj=new trie (; *obj.insert(word ); * boolean param _2=obj.search (word ); * boolean param _3=obj.starts with (prefix ); */

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。