我有一个trie实现,我想打印出我的trie,所以我可以看到它里面有什么。优选在深度优先遍历中,所以这些词实际上是有意义的。这里是我的代码:如何在Java中打印Trie?
package trie;
public class Trie {
public TrieNode root;
public Trie(){
root = new TrieNode();
}
/*
public Trie(char c){
TrieNode t = new TrieNode(c);
root = t;
}*/
public void insert(String s, int phraseNb){
int i = 0;
TrieNode node = root;
char[] string = s.toCharArray();
TrieNode child = null;
while(i < string.length){
child = node.getChild(string[i]);
if(child == null){
child = new TrieNode(string[i]);
node.addChild(child);
}
else{
node = child;
}
i++;
}
node.endOfWord();
node.setNb(phraseNb);
}
public int[] search(char[] c){
TrieNode node = root;
for(int i = 0; i < c.length-1; i++){
node = root;
int s = 0;
while(i+s < c.length){
TrieNode child = node.getChild(c[i + s]);
if(child == null){
break;
}
if(child.isWord()){
return new int[] {i, s+1, node.getNb()};
}
node = child;
s++;
}
}
return new int[] {-1, -1, -1};
}
public void print(){
}
}
package trie;
import java.io.*;
import java.util.*;
public class TrieNode {
private boolean endOfWord;
private int phraseNb;
private char letter;
private HashSet<TrieNode> children = new HashSet<TrieNode>();
public TrieNode(){}
public TrieNode(char letter){
this.letter = letter;
}
public boolean isWord(){
return endOfWord;
}
public void setNb(int nb){
phraseNb = nb;
}
public int getNb(){
return phraseNb;
}
public char getLetter(){
return letter;
}
public TrieNode getChild(char c){
for(TrieNode child: children){
if(c == child.getLetter()){
return child;
}
}
return null;
}
public Set<TrieNode> getChildren(){
return children;
}
public boolean addChild(TrieNode t){
return children.add(t);
}
public void endOfWord(){
endOfWord = true;
}
public void notEndOfWord(){
endOfWord = false;
}
}
只是一个解释如何去做它或一些伪代码是我所需要的。谢谢你的时间。
您是否熟悉深度优先遍历?这更像是关于格式化的问题。 – Antimony 2012-07-29 04:56:07
我明白它是什么,但完全不了解如何在trie中执行操作 – nain33 2012-07-29 05:32:21
提示:使用泛型 - 稍后您可以重用此代码。 – xenteros 2017-06-14 10:06:01