}
package trietree;
import java.util.LinkedList;
/*
* yy
* 1:字典树的插入
* 2:查找
* 3:统计前缀
* 4:遍历字典树
* */
public class TrieTree {
private TrieNode root;
public TrieNode getRoot() {
return root;
}
public void setRoot(TrieNode root) {
this.root = root;
}
public TrieTree(TrieNode root) {
super();
this.root = root;
}
public TrieTree() {
this.root=new TrieNode();
}
//向字典树插入一个字符串
public void insert(String str){
if(str==null||str.equalsIgnoreCase(""))return ;
TrieNode node=this.root;
char[] letters=str.toCharArray();
int len=str.length();
for(int i=0;i<len;i++){
int pos=letters[i]-'a';
if(node.getSon()[pos]==null){
node.getSon()[pos]=new TrieNode(letters[i]);
}else{
node.getSon()[pos].setNum(node.getSon()[pos].getNum()+1);
}
node=node.getSon()[pos];
}
node.setIeEnd(true);
}
//计算给定当前前缀有多少字符串
public int countPrefix(String prefix){
if(prefix==null || "".equalsIgnoreCase(prefix))return -1;
TrieNode node=this.root;
char[] letters=prefix.toCharArray();
int len=prefix.length();
for(int i=0;i<len;i++){
int pos=letters[i]-'a';
if(node.getSon()[pos]==null){
return 0;
}else{
node=node.getSon()[pos];
}
}
return node.getNum();
}
//查看当前的字典树是否包含某个单词
public boolean has(String str){
if(str==null||"".equalsIgnoreCase(str))return false;
TrieNode node=this.root;
char[] letters=str.toCharArray();
int len=str.length();
for(int i=0;i<len;i++){
int pos=letters[i]-'a';
if(node.getSon()[pos]==null){
return false;
}else{
node=node.getSon()[pos];
}
}
return node.isIeEnd();
}
//遍历当前的字典树
public void printALlWords(){
TrieNode rootnode=this.root;
if(rootnode==null)return ;
LinkedList<TrieNode> list=new LinkedList<TrieNode>();
for(int i=0;i<26;i++){
TrieNode node=rootnode.getSon()[i];
if(node!=null){
list.addLast(node);
while(!list.isEmpty()){
TrieNode current=list.getLast();
TrieNode firstChild=firstOfChild(current);
while(firstChild!=null){
list.addLast(firstChild);
firstChild=firstOfChild(firstChild);
}
TrieNode last=list.getLast();
if(last.isIeEnd()==true){
this.printList(list);
}
list.removeLast();
}
}
list.clear();
}
}
//返回当前节点的第一个孩子
private TrieNode firstOfChild(TrieNode current) {
if(current==null)return null;
for(int i=0;i<26;i++){
if(current.getSon()[i]!=null&¤t.getSon()[i].isVisited()==false){
current.getSon()[i].setVisited(true);
return current.getSon()[i];
}
}
return null;
}
private void printList(List<TrieNode> list){
if(list==null||list.size()==0)return ;
for(TrieNode node:list){
System.out.print(node.getVal());
}
System.out.println();
}
public static void main(String[] args) {
TrieTree tree=new TrieTree();
String[] strs={"bee","banana", "band","absolute", "acm"}; //
String[] prefix={
"ba",
"b",
"band",
"abc"
};
for(String s:strs){
tree.insert(s);
}
for(String pre:prefix){
System.out.println(pre+":"+tree.countPrefix(pre));
}
System.out.println(tree.has("banana"));
System.out.println(tree.has("ba"));
tree.printALlWords();
}
}