nym_kalahi nym_kalahi - 4 years ago 153
C++ Question

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;
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!

Answer Source
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download