【问题标题】:Get Height of binary search tree recursively [closed]递归获取二叉搜索树的高度[关闭]
【发布时间】:2018-05-06 13:32:34
【问题描述】:

我一直在尝试制作一个函数来以递归方式获取二叉树的高度。

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;
    }
}

我调试了我的代码,但由于某种原因,我在“if condition”行出现了访问冲突错误。我不明白为什么我仍然收到此错误。我想它的发生是因为我的左边或右边之一为空,但我看不到其他方法。 这是我将节点插入树的函数:

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;
}

【问题讨论】:

  • 使用调试器。在询问之前始终使用调试器。
  • 假设leftright 中只有一个为空?
  • 我调试了我的代码,但由于某种原因,出现了访问冲突错误。调用堆栈以查看导致访问冲突的代码行。我希望 gdb 也会这样做。
  • @drescherjm 我修复了这个帖子。该行是 if 条件。
  • BTW,访问成员时不需要使用this-&gt;语法;仅在成员与参数同名时使用(在这种情况下,重命名参数)。

标签: c++ recursion binary-search-tree


【解决方案1】:

if 语句中条件的否定

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-&gt;_leftthis-&gt;_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());
}

【讨论】:

  • 非常感谢!我明白我错在哪里了。修复了我的代码。
  • @I.Klein 完全没有。不客气。:)
  • @drescherjm 我接受了。
猜你喜欢
  • 1970-01-01
  • 2019-09-02
  • 2015-04-08
  • 2014-01-02
  • 2018-09-16
  • 2022-06-14
  • 1970-01-01
  • 1970-01-01
  • 2014-10-17
相关资源
最近更新 更多