计算二叉搜索树的高度
Calculating Height of Binary Search Tree
我一直在寻找如何计算二叉搜索树的高度,我的研究使我得到了以下实现。我还在想为什么它会起作用,但我也不确定为什么它不起作用。这是我的高度函数。
int BinaryTreeNode::height() const {
int lefth = left->height();
int righth = right->height();
if(lefth > righth) {
return lefth + 1;
} else {
return righth + 1;
}
}
这是节点
的类定义class BinaryTreeNode {
public:
Data * nodeData;
BinaryTreeNode * left;
BinaryTreeNode * right;
当我试图运行它我的程序锁定和崩溃。我错过了什么明显的东西吗?
编辑:为什么这不能工作?
int BinaryTreeNode::height() const {
int l = 0;
if (left != NULL) {
left->height();
}
int r = 0;
if (right != NULL) {
right->height();
}
if (l > r) {
return l + 1;
}
else {
return r + 1;
}
}
你的树不是无限的。所以,我假设一些节点没有左或右子节点,指针left
和/或right
在这种情况下是空的。在使用它们之前,您必须检查它们是否存在。
试试这个函数:
int BinaryTreeNode::height()
{
int l = left ? left->height() : 0; // height of left child, if any
int r = right ? right->height() : 0; // idem for right child
return 1 + max(l, r);
}
注意:我已经简化了你的高度计算。
问题是你的函数从不检查子指针是否为NULL
,所以除了解引用无效指针之外,你有一个错过基本情况的递归函数:
试试这个版本:
int BinaryTreeNode::height() const
{
int lefth = 0;
if (left != NULL) { lefth = left->height(); }
int righth = 0;
if (righth != NULL) { righth = right->height(); }
if (lefth > righth) { return lefth + 1; }
else { return righth + 1; }
}
甚至我也面临着同样的问题,你的代码的问题是,在你的函数中,你使用递归两次,你要去左右两个极端,但你没有检查的可能性,如果在左子树的父节点之一的右子节点有自己的子节点,因此你没有遍历到最后一个叶节点在你的树!希望对大家有所帮助
相关文章:
- 有根的二进制搜索树.保留与其父级的链接
- 正在尝试重载二进制搜索树分配运算符
- 使用C++创建特殊的二叉搜索树
- 在递归二叉搜索树中搜索
- 在二叉搜索树中插入时出现分段错误
- C++二叉搜索树模板从函数返回节点
- 我可以在没有堆栈的情况下在二叉搜索树中实现迭代器吗?
- 在二叉搜索树C++中计算平均值
- 在字符串的二叉搜索树中搜索子字符串 - C++
- 在二叉搜索树中插入新元素
- 如何打印在二叉搜索树中找到的数据?
- 查找存储在二叉搜索树的所有非叶子中的数据总和?(返回整数的独立递归函数
- 这是一个二叉搜索树吗?黑客排名问题
- 二叉搜索树 - 实现"search"函数
- 递归获取二进制搜索树的高度
- 二叉搜索树中的高度函数
- 二叉搜索树的总高度
- 二进制搜索树,高度
- 计数高度为h的二叉搜索树对n个元素的所有可能的根的个数
- 计算二叉搜索树的高度