递归获取二进制搜索树的高度

Get Height of binary search tree recursively

本文关键字:高度 搜索树 二进制 获取 递归      更新时间:2023-10-16

我一直在尝试以递归方式获得二进制树的高度。

int BSNode::getHeight() const //Returns the height of the tree.
{
    if (this->_left == nullptr && this->_right == nullptr)
    {
        return 0;
    }
    else
    {
        return std::max(this->_left->getHeight(), this->_right->getHeight()) + 1;
    }
}

我调试了我的代码,出于某种原因,我在"如果条件"行上出现了访问违规错误。我看不出为什么我仍然会遇到这个错误。我想这是因为我的左或右零之一是无效的,但是我看不到其他方法。这是将节点插入树的功能:

void BSNode::insert(string value) //Inserts node to the tree.
{
    if (value > this->_data)
    {
        if (this->_right != NULL)
        {
            this->_right->insert(value);
        }
        else
        {
            this->_right = new BSNode(value);
        }
    }
    else if (value < this->_data)
    {
        if (this->_left != NULL)
        {
            this->_left->insert(value);
        }
        else
        {
            this->_left = new BSNode(value);
        }
    }
}

这是我建造的类:

class BSNode
{
    private:
        string _data;
        BSNode* _left;
        BSNode* _right;
}

如果语句

if (this->_left == nullptr && this->_right == nullptr)

else if ( not ( this->_left == nullptr && this->_right == nullptr) )

反过来等同于

else if ( this->_left != nullptr || this->_right != nullptr )

但是,在函数中, this->_leftthis->_right可以等于nullptr。

    return std::max(this->_left->getHeight(), this->_right->getHeight()) + 1;

还不清楚为什么高度具有签名的类型int,而不是某些无符号类型,例如size_t

我想树的头总是与nullptr不相等。否则,您应该使用一个参数重写函数为静态成员函数:指向头节点的指针。

该功能可以看起来以下方式

size_t BSNode::getHeight() const //Returns the height of the tree.
{
        return  1 + std::max(
                this->_left  == nullptr ? 0 : this->_left->getHeight(), 
                this->_right == nullptr ? 0 : this->_right->getHeight());
}