Binary tree height function

I am working on a function to find the height of a binary search tree. I found a method that seems to work, but I keep getting this error, and I don’t know what is wrong with it: Unhandled exception at 0x00903417 in PA5.exe: 0xC0000005: Location for detecting access violation 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 an implementation in the main function ...

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

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

+4
source share
4 answers
 if (node = NULL) 

it should be

 if (node == NULL) 

because in C ++ = there is an assignment operator, and == is a relational operator for comparison.

Why an accident?

When you execute if (node = NULL) , you assign NULL to node, and since NULL is 0 , the if condition fails. So, you go ahead and call the function recursively on the child nodes. Now suppose node was actually NULL when the function was called for the first time, you will make recursive calls for NULL left and right children !!! Overcoming the collapse.

+6
source

You assign null to your node parameter variable in the if statement.

 if (node = NULL) { return 0; } 

it should be

 if(node == NULL) ... 
+1
source

Tree Search Height Method (BST): for both the left subtree and the right subtree ::

Put the elements you want to put in your binary tree into an array before creating the actual tree. Calculate the number of elements that are larger than the root, which will go to the left of the tree and similarly to the right side.

Then add the elements to the tree. Each time, set the flag bit to 1 or 0 depending on whether you add it to the left subtree or to the right.

 if(root->right && flagleft==1) no_left--; else if(root->right && flagright==1) no_right--; 

This is when adding node to the left side.

 if(root->left && flagl==1) nl--; else if(root->left && flagr==1) nr--; 

This is until you add node to the right side.

+1
source

This is due to the fact that you assigned the value node NULL ie NULL - 0, so the condition is not met.

do if (node ​​== NULL) instead if (node ​​= NULL)

0
source

Source: https://habr.com/ru/post/1441703/


All Articles