Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary Tree Height Function

I'm working on a function to find the height of a binary search tree. I found a method that seems like it should work, but I keep getting this error, and I don't know whats wrong with it: Unhandled exception at 0x00903417 in PA5.exe: 0xC0000005: Access violation reading location 0x00000004.

Here are my height functions...

template <class T>
int BST<T>::height()
{

    return displayHeight(mRootNode);    

}

template <class T>
int BST<T>::displayHeight(BST<T> *node)
{
    if (node = NULL)
    {
        return 0;
    }

    int left = displayHeight(node->mLeft);
    int right = displayHeight(node->mRight); 

    if (left > right)
        return 1 + left;
    else
        return 1 + right;
}

This is the implementation in the main function...

 cout << endl << "height: " << tree.height();

If I should include anything else, let me know. Thanks!

like image 261
nym_kalahi Avatar asked Jan 16 '23 05:01

nym_kalahi


2 Answers

if (node = NULL)

should be

if (node == NULL)

because in C++ = is an assignment operator and == is the relational operator for comparison.

Why the crash?

When you do if (node = NULL), you are assigning NULL to node and since NULL is 0 the if condition fails. So you go ahead and call the function recursively on the nodes's children. Now suppose node was actually NULL when the function was called for the first time, you'll be doing the recursive calls on NULL's left and right children!!! Leading to crash.

like image 129
codaddict Avatar answered Jan 20 '23 10:01

codaddict


You are assigning null to your node parameter variable in your if statement.

if (node = NULL)
{
    return 0;
}

should be

if(node == NULL) ...
like image 41
Jake H Avatar answered Jan 20 '23 09:01

Jake H