I have a trie where each node is an object TrieNode
like this:
public char content;
public double count;
public LinkedList<TrieNode> childList;
I had to count the occurrence of a specific char in the trie.
I think to sum the count
field of nodes that have content = char
I'm looking for.
So this is what I've done:
int occ = occurrencesOfChar(0, root, c);
public int occurrencesOfChar(int occ, TrieNode node, char c) {
for(TrieNode child : node.childList) {
if(child.content == c) {
occ += child.count;
}
occ += occurrencesOfChar(occ, child, c);
}
return occ;
}
But the result is overestimated, returns more occurences than those that actually are. Why?
You're adding to occ
multiple times because you're passing it as a parameter.
You should use a local variable:
public int occurrencesOfChar(TrieNode node, char c) {
int occ = 0;
for(TrieNode child : node.childList) {
if(child.content == c) {
occ += child.count;
}
occ += occurrencesOfChar(child, c);
}
return occ;
}