<分区>
我一直在尝试制作一个函数以递归方式获取二叉树的高度。
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;
}