1

Why are we returning -1 whenthere is no node or nullptr? I cant figure out its logic and how will it cancel with the +1

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

    else 
        return 1 + std::max( height( node->left ), height( node->right ) );
    }
  • If one of the two nodes is not null, than the `height` of that subtree will return something larger than or equal to `0`, hence the `max` will *never* pick the `-1`. – Willem Van Onsem Nov 16 '19 at 12:10

1 Answers1

2

The function has a logical error.

If the head node is not equal to nullptr but has no childs the function returns 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

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.

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. For example

size_t height( const BinaryNode * node ) const 
{
    return node == nullptr ? 0 : 1 + std::max( height( node->left ), height( node->right ) );
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335