【问题标题】:How can i count total number of nodes in a trie data structure如何计算特里数据结构中的节点总数
【发布时间】:2019-07-21 07:13:11
【问题描述】:

我尝试了这种方法,但不起作用。请帮我解决这个问题

static int count=0;

static void insert(String key) {
    int level, length = key.length(), index;
    TrieNode pCrawl = root;

    for (level = 0; level < length; level++) {
       index = key.charAt(level) - 'a';
       if (pCrawl.children[index] == null) {
           pCrawl.children[index] = new TrieNode();
       }

       pCrawl = pCrawl.children[index];
    }

    pCrawl.isEndOfWord = true;
}

【问题讨论】:

  • “不起作用”是什么意思?你有错误吗?你得到了意想不到的结果吗?
  • 你永远不会增加计数器...
  • 除此之外,为什么在插入元素时需要计算树中的节点?为什么insert(...)-方法是静态的?你有这棵树的一个实例吗?如果是这样,我建议使用Singleton pattern
  • 完全不清楚你在问什么。问题询问如何计算节点,但您向我们展示了一个绝对与计数无关的insert 方法。什么给了?

标签: java data-structures trie


【解决方案1】:

只需添加一个全局变量 count 并在插入字符串时创建新节点时将其递增。现在您不必编写单独的函数来计算树中的节点了。

 int count = 0;
 static void insert(String key) {
    int level, length = key.length(), index;
    TrieNode pCrawl = root;
    for (level = 0; level < length; level++) {
       index = key.charAt(level) - 'a';
       if (pCrawl.children[index] == null) {
           pCrawl.children[index] = new TrieNode();
           count++;
       }
       pCrawl = pCrawl.children[index];
    }
    pCrawl.isEndOfWord = true;
}

【讨论】:

    猜你喜欢
    • 2010-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-02
    • 2016-06-23
    • 2011-03-24
    • 1970-01-01
    相关资源
    最近更新 更多