【问题标题】:Total height of a binary search tree二叉搜索树的总高度
【发布时间】: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


【解决方案1】:

这里有一个问题:

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

【讨论】:

  • 我一开始也是这么想的,关于处理只有left或right为NULL但不是两者都为NULL的情况,但从技术上讲,它已经被处理了。第一个 if 检查返回 -1 并且 max() 调用“过滤”出来。这也假设“findHeight”应该是“getHeight”。
  • 对,我稍微修正了我的代码。我们不需要知道这个神秘的findHeight 就能计算高度。
  • 抱歉,我将 findHeight 重命名为 getHeight 并忘记在递归中对其进行编辑。谢谢。
  • @Dalkurac 如果此答案解决了问题,请不要忘记接受答案。
  • 现在的问题在于它没有在我的主函数中返回一个 int。让我来解决它,如果我不能修复它,我会发布我所拥有的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多