二叉搜索树的总高度
Total height of a binary search tree
我正在构建一个二叉搜索树,我想创建一个函数来记录每个节点的高度并将其求和。我正在尝试使用递归。
对我来说,困难在于为每个节点分配一个高度,然后回过头来总结一下。除非我可以一次性分配和记录高度?提前谢谢。
编辑:最终代码,以显示对将来将要查看此内容的任何人有用的内容。谢谢你们的帮助。
BST.h
int totalheight(node);
int getHeight(node);
class BST {
Node root;
public:
BST { root = NULL; }
int totalheight()
{ return ::totalheight(root);
};
BST.cpp
int totalHeight(BSTNode* node)
{
if (node == NULL)
return -1;
int leftHeight = getheight(node->left);
int rightHeight = getheight(node->right);
int totalheight = 1 + leftHeight + rightHeight; // +1 to count the root
return totalheight;
}
int getheight(BSTNode* node)
{
if (node == NULL)
return 0;
return 1 + max(getheight(node->left), getheight(node->right));
}
main.cpp
int main() {
BST tree; // and various inserts
tree.totalheight();
} // main
这里有一个问题:
int myheight = max(leftheight, rightheight);
它应该是:
int myheight = max(leftheight, rightheight) + 1;
您需要一个来适应此节点高度。同样在显示递归的代码中,findHeight
应该getHeight
。
这是一个整体功能:
int getheight(BSTNode* node)
{
if (node == null)
return 0;
else
return 1 + max(getHeight(node->left), getHeight(node->right));
} // getheight
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 正在尝试重载二进制搜索树分配运算符
- 使用C++创建特殊的二叉搜索树
- 在递归二叉搜索树中搜索
- 在二叉搜索树中插入时出现分段错误
- C++二叉搜索树模板从函数返回节点
- 我可以在没有堆栈的情况下在二叉搜索树中实现迭代器吗?
- 在二叉搜索树C++中计算平均值
- 在字符串的二叉搜索树中搜索子字符串 - C++
- 在二叉搜索树中插入新元素
- 如何打印在二叉搜索树中找到的数据?
- 查找存储在二叉搜索树的所有非叶子中的数据总和?(返回整数的独立递归函数
- 这是一个二叉搜索树吗?黑客排名问题
- 二叉搜索树 - 实现"search"函数
- 递归获取二进制搜索树的高度
- 二叉搜索树中的高度函数
- 二叉搜索树的总高度
- 二进制搜索树,高度
- 计数高度为h的二叉搜索树对n个元素的所有可能的根的个数
- 计算二叉搜索树的高度