如何递归地找到Trie树的高度
How to recursivly find the height of a Trie Tree
我在弄清楚如何找到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函数,但在直接实现中,使用它会导致多次计算同一子节点的高度。
相关文章:
- 这个极客对极客的trie实现是否存在内存泄漏问题
- 在 c++ 中实现 Trie 时出现分段错误
- Trie*& 和 Trie** 的意思是 Same?
- C++:如何根据地形高度更新玩家身高?
- Trie 树初始化
- 如何更改QComboBox项目的高度大小?
- 更改高度贴图,使其在 4x4 网格上显示 16 个 hieghtmap
- 我试图用这段代码找到二叉树的高度,但它一直返回 0,有人可以告诉我为什么吗?
- C++:如何计算二叉树中其值模块高度小于 2 的节点数?
- 在我的trie实现中出现分段错误
- 如何使用 C++ gdal 库将栅格地理从 EGM96 转换为 WGS84 椭球体高度基准面
- 使用 trie 数据结构链接不同类型的信息
- 从具有父指针和左子树和右子树高度的树中删除
- 程序输入名称和高度并显示它。我不知道如何显示列表中最高人的姓名和身高
- C++ 中的 TRIE 数据结构实现
- 我正在尝试创建一个 C++ 贪吃蛇游戏,但我似乎无法绘制第二个高度边框,我该如何解决这个问题?
- 计算树高度的函数
- 尝试创建一个程序来查找非二叉树的高度.最终得到一个很长的循环,没有答案
- 计算BST返回-1的高度混淆
- 如何递归地找到Trie树的高度