gpt4 book ai didi

c++ - 二叉搜索树的总高度

转载 作者:行者123 更新时间:2023-11-30 04:13:39 25 4
gpt4 key购买 nike

我正在构建一个二叉搜索树,我想创建一个函数来记录每个节点的高度并对其求和。我正在尝试使用递归。

对我来说,难点在于给每个节点分配一个高度,然后回过头来总结。除非我可以一次分配并记录高度?提前致谢。

编辑:最终代码展示了对我有用的东西,供将来查看此内容的任何人使用。感谢大家的帮助。

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++ - 二叉搜索树的总高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19320657/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com