计算一个节点在 trie 数据结构中出现的次数
Count number of occurence of a node in a trie data structure
我有一个 trie,其中每个节点都是一个对象 TrieNode
,如下所示:
public char content;
public double count;
public LinkedList<TrieNode> childList;
我必须计算特定字符在 trie 中的出现次数。
我想对具有 content = char
我正在寻找的节点的 count
字段求和。
这就是我所做的:
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;
}
但结果被高估了,returns 比实际发生的次数多。
为什么?
您多次向 occ
添加,因为您将其作为参数传递。
您应该使用局部变量:
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;
}
我有一个 trie,其中每个节点都是一个对象 TrieNode
,如下所示:
public char content;
public double count;
public LinkedList<TrieNode> childList;
我必须计算特定字符在 trie 中的出现次数。
我想对具有 content = char
我正在寻找的节点的 count
字段求和。
这就是我所做的:
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;
}
但结果被高估了,returns 比实际发生的次数多。 为什么?
您多次向 occ
添加,因为您将其作为参数传递。
您应该使用局部变量:
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;
}