如何递归地找到Trie Tree的高度

时间:2014-10-15 21:57:44

标签: c++ tree height trie

我在弄清楚如何找到特里树数据结构的高度时遇到了一些麻烦。我知道对于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
  }
} 

2 个答案:

答案 0 :(得分:2)

循环是要走的路。

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 ++&lt; 11。

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;

答案 1 :(得分: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函数,但在使用它的直接实现中会导致多次计算同一子节点的高度。