计算二叉搜索树的高度

Calculating Height of Binary Search Tree

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

我一直在寻找如何计算二叉搜索树的高度,我的研究使我得到了以下实现。我还在想为什么它会起作用,但我也不确定为什么它不起作用。这是我的高度函数。

int BinaryTreeNode::height() const {
    int lefth = left->height();
    int righth = right->height();
    if(lefth > righth) {
        return lefth + 1;
    } else {
        return righth + 1;
    }
}
这是节点 的类定义
class BinaryTreeNode {
  public:
    Data * nodeData;
    BinaryTreeNode * left;
    BinaryTreeNode * right;

当我试图运行它我的程序锁定和崩溃。我错过了什么明显的东西吗?

编辑:为什么这不能工作?

int BinaryTreeNode::height() const {
    int l = 0;
    if (left != NULL) {
        left->height();
    }
    int r = 0;
    if (right != NULL) {
        right->height();
    }
    if (l > r) {
        return l + 1;
    }
    else {
        return r + 1;
    }
}

你的树不是无限的。所以,我假设一些节点没有左或右子节点,指针left和/或right在这种情况下是空的。在使用它们之前,您必须检查它们是否存在。

试试这个函数:

int BinaryTreeNode::height()
{
    int l = left ? left->height() : 0;  // height of left child, if any
    int r = right ? right->height() : 0; // idem for right child
    return 1 + max(l, r);
}

注意:我已经简化了你的高度计算。

问题是你的函数从不检查子指针是否为NULL,所以除了解引用无效指针之外,你有一个错过基本情况的递归函数:

试试这个版本:

int BinaryTreeNode::height() const 
{
    int lefth = 0;
    if (left != NULL) { lefth = left->height(); }
    int righth = 0;
    if (righth != NULL) { righth = right->height(); }
    if (lefth > righth) { return lefth + 1; } 
    else { return righth + 1; }
}

甚至我也面临着同样的问题,你的代码的问题是,在你的函数中,你使用递归两次,你要去左右两个极端,但你没有检查的可能性,如果在左子树的父节点之一的右子节点有自己的子节点,因此你没有遍历到最后一个叶节点在你的树!希望对大家有所帮助