c++ - 计算返回 -1 混淆的 BST 的高度?

标签 c++ algorithm binary-tree binary-search-tree

为什么我们在没有节点或 nullptr 时返回 -1?我无法弄清楚它的逻辑以及它如何用 +1 取消

int height( BinaryNode * node ) const {
    if ( node == nullptr ) 
        return -1;

    else 
        return 1 + std::max( height( node->left ), height( node->right ) );
    }

最佳答案

函数有逻辑错误。

如果头节点不等于 nullptr 但没有子节点,则函数返回 0。但是,如果有 child ,则头节点会被反击。

    return 1 + std::max( height( node->left ), height( node->right ) );
          ^^^

像这样重写函数就可以了

int height( BinaryNode * node ) const 
{
    return node == nullptr ? 0 : 1 + std::max( height( node->left ), height( node->right ) );
}

或者

int height( const BinaryNode * node ) const 
{
    return node == nullptr ? 0 : 1 + std::max( height( node->left ), height( node->right ) );
}

因为树没有被这个函数改变。

由于树的高度不能为负,因此最好将返回类型设置为 unsigned int 或 size_t。例如

size_t height( const BinaryNode * node ) const 
{
    return node == nullptr ? 0 : 1 + std::max( height( node->left ), height( node->right ) );
}

关于c++ - 计算返回 -1 混淆的 BST 的高度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58890563/

相关文章:

c++ - 在数组中查找 y 的 x 个连续值的最有效方法是什么?

c - 将级别顺序插入到二叉树中?

c - 如何使用 XOR 查找数组中出现次数为奇数的单个元素?

java - 简单的二叉树问题

c - 二叉树代码无法正常工作

c++ - 奇怪的 unsigned long long int 行为

c++ - 将多维数组传递给 C++ 中的函数

c++ - 为什么 unsigned int 0xFFFFFFFF 等于 int -1?

c++ - 提取给定坐标内的像素

algorithm - 是什么使树遍历预序或有序?