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!
should be
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 assigningNULLto node and since NULL is0theifcondition fails. So you go ahead and call the function recursively on the nodes’s children. Now supposenodewas 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.