我写了以下前缀特里:
class TrieNode {
char letter;
HashMap<Character,TrieNode> children;
boolean fullWord;
TrieNode(char letter) {
this.letter = letter;
children = new HashMap<Character, TrieNode>();
this.fullWord = false;
}
}
class Tree{
static TrieNode createTree() {
return (new TrieNode('\0'));
}
static void insertWord(TrieNode root, String word) {
int l = word.length();
char[] letters = word.toCharArray();
TrieNode curNode = root;
for (int i = 0; i < l; i++) {
if (!curNode.children.containsKey(letters[i]))
curNode.children.put(letters[i], new TrieNode(letters[i]));
curNode = curNode.children.get(letters[i]);
}
curNode.fullWord = true;
}
}
我想添加 DFS 方法以查找具有多个子节点的第一个节点(因此它会显示最长的公共前缀)。
我写了这段代码:
static void DFS(TrieNode node) {
for (TrieNode tn: node.children.values()){
DFS(tn);
if (node.children.size()>2)
System.out.println("found the first vertex");
}
}
但它不起作用。我究竟做错了什么?