trie树 java实现_trie树的java实现

一个简单的trie tree数据结构

public class Trie {

static class TrieNode

{

private int count;

private byte c;

private TrieNode[] children;

private int wid=0;

public TrieNode(int width)

{

children=new TrieNode[width];

count=0;

wid=width;

c=(byte)0;

}

public int getCount()

{

return count;

}

public void setCount(int ct)

{

count=ct;

}

public byte getByte()

{

return c;

}

public void setByte(byte b)

{

c=b;

}

public TrieNode[] getChildren()

{

return children;

}

public void setChildren(TrieNode[] nodes)

{

children=nodes;

}

public void add(byte[] bts, int i) {

if(i>=bts.length)

{

this.count++;

}else

{

for(int j=0;j

{

if(this.children[j]==null)

{

this.children[j]=new TrieNode(wid);

this.children[j].setByte(bts[i]);

this.children[j].add(bts, i+1);

break;

}else if(this.children[j].getByte()==bts[i])

{

this.children[j].add(bts, i+1);

break;

}

}

}

}

public int getCount(byte[] bts, int i) {

if(i>=bts.length)

{

return this.getCount();

}else

{

for(int j=0;j

{

if(this.children[j]==null)

{

return -1;

}

if(this.children[j].getByte()==bts[i])

{

return this.children[j].getCount(bts,i+1);

}

}

}

return -1;

}

}

private int width;

private TrieNode root;

public Trie(int width)

{

this.width=width;

root=new TrieNode(this.width);

}

public void add(byte[] bts)

{

for(int i=0;i

{

if(root.getChildren()[i]==null)

{

root.getChildren()[i]=new TrieNode(width);

root.getChildren()[i].setByte(bts[0]);

root.getChildren()[i].add(bts, 1);

break;

}else if(root.getChildren()[i].getByte()==bts[0])

{

root.getChildren()[i].add(bts, 1);

break;

}

}

}

public int getCount(byte[] bts)

{

for(int i=0;i

{

if(root.getChildren()[i]==null)

{

return -1;

}

if(root.getChildren()[i].getByte()==bts[0])

{

return root.getChildren()[i].getCount(bts, 1);

}

}

return -1;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值