我正在构建一个二叉搜索树,我想创建一个记录每个节点高度并对其进行求和的函数。我正在尝试使用递归。二叉搜索树的总高度
对我来说,困难在于给每个节点分配一个高度,然后返回并对其进行总结。除非我能一次性分配和记录高度?提前致谢。
编辑:最终代码显示对于任何将来查看此内容的人而言,我的工作方式。谢谢你们的帮助。
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()'...这有点混乱。 – Angew
看起来你主要有命名和语法问题,并且在战略性的地方忘了'+ 1'。 – molbdnilo
已修复,请参阅上文。我包括我的头文件,看看我从main调用它。 – Dalkurac