トライの実装があり、トライを印刷して、その内容を確認したいと考えています。単語が実際に意味をなすように、深さ優先のトラバーサルが望ましいです。これが私のコードです:
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;
}
}
それを行う方法についての説明またはいくつかの擬似コードが必要です。御時間ありがとうございます。