递归获取二进制搜索树的高度
Get Height of binary search tree recursively
我一直在尝试以递归方式获得二进制树的高度。
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->_left
或 this->_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());
}
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 正在尝试重载二进制搜索树分配运算符
- 使用C++创建特殊的二叉搜索树
- 在递归二叉搜索树中搜索
- 在二叉搜索树中插入时出现分段错误
- C++二叉搜索树模板从函数返回节点
- 我可以在没有堆栈的情况下在二叉搜索树中实现迭代器吗?
- 在二叉搜索树C++中计算平均值
- 在字符串的二叉搜索树中搜索子字符串 - C++
- 在二叉搜索树中插入新元素
- 如何打印在二叉搜索树中找到的数据?
- 查找存储在二叉搜索树的所有非叶子中的数据总和?(返回整数的独立递归函数
- 这是一个二叉搜索树吗?黑客排名问题
- 二叉搜索树 - 实现"search"函数
- 递归获取二进制搜索树的高度
- 二叉搜索树中的高度函数
- 二叉搜索树的总高度
- 二进制搜索树,高度
- 计数高度为h的二叉搜索树对n个元素的所有可能的根的个数
- 计算二叉搜索树的高度