【问题标题】:How to recursivly find the height of a Trie Tree如何递归地找到特里树的高度
【发布时间】:2014-10-15 21:57:43
【问题描述】:

我在弄清楚如何找到特里树数据结构的高度时遇到了一些麻烦。我知道对于 AVL 树,一个简单的递归高度函数是:

height(nodeType *node) const
{
  if(node == NULL)
    return 0;

  // if tree is not empty height is 1 + max of either path
  return 1 + std::max(height(node->left), height(node->right));
}

但是现在我的 trie 树有一个具有 26 个不同索引的子节点,必须有一种简单的方法来找到最大高度,而无需输入所有 26 个不同的可能索引。我该怎么办?

int height(trieNodeType *node) const
{
  if(node == NULL)
    return 0;

  for(int i = 0; i < 26; i ++) {
    //has to be something to do with a for loop, 
    //i know that much
  }
} 

【问题讨论】:

  • trieNodeType的定义是什么?
  • @cdhowie 它包含一个值,布尔值和trieNodeType *children[26]

标签: c++ tree height trie


【解决方案1】:

循环是要走的路。

C++11:

if (node == nullptr) return 0;

auto i = std::begin(node->children);
auto end = std::end(node->children);

auto max_height = height(i++);

while (i != end) {
    max_height = std::max(max_height, height(i++));
}

return 1 + max_height;

C++

if (node == NULL) return 0;

trieNodeType ** i = node->children;
trieNodeType ** end = i + (sizeof(node->children) / sizeof(trieNodeType *));

int max_height = height(i++);

while (i != end) {
    max_height = std::max(max_height, height(i++));
}

return 1 + max_height;

【讨论】:

  • 在 c++11 之前的代码中,我必须将 i 和 end 更改为 node-&gt;children[0] 和 node->children[25]`,但程序挂起并崩溃。有什么想法吗?
  • @SyntacticFructose 我的错,iend 应该是指向指针的指针。试试更新的代码。
【解决方案2】:

另一种 C++11 方法

return 1 + std::accumulate(std::begin(node->children) + 1, std::end(node->children), 
    height(node->children[0]),
    [](int curMax, trieNodeType* child) { return std::max(curMax, height(child)); });

还有std::max_element函数,但是在直接实现中使用它会导致多次计算同一个子节点的高度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-16
    • 1970-01-01
    • 2019-05-18
    • 2012-10-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多