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

How to recursivly find the height of a Trie Tree

本文关键字:Trie 高度 何递归 递归      更新时间:2023-10-16

我在弄清楚如何找到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
  }
} 

循环是最好的方法。

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

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