我有一个 trie 实现,我想打印出我的 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;
}
}
我只需要一个关于如何去做的解释或一些伪代码。谢谢你的时间。