int count=0;
public int countwords(TrieNode root){
if (root.isTerminating==true)
count++;
for (int i=0;i<26;i++){
if (root.children[i]!=null)
countwords(root.children[i]);
}
return count;
}
这个函数用于计算 trie 中的单词数,它给了我错误的答案,这里出了什么问题?我使用 isTerminate 来区分单词和另一个单词。
最佳答案
public int countwords(TrieNode root) {
// variable localized because it is a recursive call
// also because we add to this variable in the loop
int count = 0;
// if condition simplified
if (root.isTerminating)
count++;
for (int i = 0; i < 26; i++) {
if (root.children[i] != null)
// you need to save the result of the recursive call
count += countwords(root.children[i]);
}
return count;
}
关于java - 计算 Trie 中的单词数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61447716/