【发布时间】:2013-10-19 16:22:39
【问题描述】:
我正在构建一个二叉搜索树,我想创建一个函数来记录每个节点的高度并将其求和。我正在尝试使用递归。
对我来说,困难在于给每个节点分配一个高度,然后再回过头来总结。除非我可以一次性指定并记录高度?提前致谢。
编辑:最终代码显示对任何将来会查看此内容的人来说对我有用的内容。谢谢大家的帮助。
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
【问题讨论】:
-
你能把代码整理一下吗?
totalheight()不带参数,totalheigh(BSTNode*),findheight(),getheight()……有点乱。 -
看起来您主要是遇到命名和语法问题,并且在战略位置忘记了
+ 1。 -
已修复,见上文。我包含了我的头文件,看看我是如何从 main 调用它的。
标签: c++ recursion height binary-search-tree