【问题标题】:Count number of occurence of a node in a trie data structure计算一个节点在 trie 数据结构中出现的次数
【发布时间】:2016-06-23 00:35:47
【问题描述】:

我有一个 trie,其中每个节点都是一个对象 TrieNode,如下所示:

public char content; 
public double count;
public LinkedList<TrieNode> childList; 

我必须计算 trie 中特定字符的出现次数。 我想总结 count 我正在寻找的具有 content = char 的节点字段。

这就是我所做的:

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;
}

但结果被高估了,返回的出现次数比实际出现的次数多。 为什么?

【问题讨论】:

  • @MartinBroadhurst 嗯不,因为在每个节点的count 字段中可以是一个大于 1 的数字。

标签: java trie


【解决方案1】:

您多次添加到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;
}

【讨论】:

  • 谢谢马丁布罗德赫斯特!
猜你喜欢
  • 2011-11-18
  • 1970-01-01
  • 1970-01-01
  • 2011-04-30
  • 2011-03-24
  • 2020-03-09
  • 2023-03-24
  • 1970-01-01
  • 2016-03-16
相关资源
最近更新 更多