二叉搜索树的总高度

Total height of a binary search tree

本文关键字:高度 搜索树      更新时间:2023-10-16

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

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

编辑:最终代码,以显示对将来将要查看此内容的任何人有用的内容。谢谢你们的帮助。

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