【发布时间】: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;
}
【问题讨论】:
-
使用调试器。在询问之前始终使用调试器。
-
假设
left和right中只有一个为空? -
我调试了我的代码,但由于某种原因,出现了访问冲突错误。调用堆栈以查看导致访问冲突的代码行。我希望 gdb 也会这样做。
-
@drescherjm 我修复了这个帖子。该行是 if 条件。
-
BTW,访问成员时不需要使用
this->语法;仅在成员与参数同名时使用(在这种情况下,重命名参数)。
标签: c++ recursion binary-search-tree