简体   繁体   English

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

[英]Calculating height of a BST returning -1 confusion?

Why are we returning -1 whenthere is no node or nullptr?为什么我们在没有节点或 nullptr 时返回 -1? I cant figure out its logic and how will it cancel with the +1我无法弄清楚它的逻辑以及它将如何用 +1 取消

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

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

The function has a logical error. function 出现逻辑错误。

If the head node is not equal to nullptr but has no childs the function returns 0 .如果头节点不等于nullptr但没有子节点,则 function 返回0 However if there are childs then the head node is countered.但是,如果有子节点,则头节点将被反击。

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

Just rewrite the function like只需像这样重写 function

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

Or或者

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

because the tree is not changed by this function.因为这个 function 没有改变树。

As the height of the tree can not be negative then it is better to make the return type either as unsigned int or size_t.由于树的高度不能为负,因此最好将返回类型设为 unsigned int 或 size_t。 For example例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM