Help with counting leaves in binary tree function

  • (2 Pages)
  • +
  • 1
  • 2

16 Replies - 406 Views - Last Post: 07 November 2017 - 03:10 PM Rate Topic: -----

#16 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2009
  • View blog
  • Posts: 5,387
  • Joined: 27-December 05

Re: Help with counting leaves in binary tree function

Posted 07 November 2017 - 03:02 PM

Next, I'm guessing that the part you omitted mentioning about your "unhandled exception" was something like "access violation reading location ..."

That means something in your program is trying to access a portion of your computer memory that doesn't belong to it. One common cause of that is trying to access the memory pointed to by a null pointer. In other words, trying to read (or write) to memory address Ox0. (zero)

So what in your code does that?

Look at this:
template <class T>
int BinaryTree<T>::countLeaves(TreeNode* nodePtr)
{
	if (root == NULL)                       //If the there is nothing in the tree return 0.
		return 0;
	if (!root->right && !root->left)        // Seeing if the the node is a leaf or not, if it is to return 1
		return 1;
	return (countLeaves(root->right) + countLeaves(root->left)); //returng the number of times the countLeaves program will have to run to reach the leaves.
}



(I took your code from Post #1 and negated the conditions on line 6.) So it returns 1 if BOTH root->right and root->left are null pointers. But what happens if only 1 of them is null? It doesn't return. Instead it goes on to the next line (line 8) and tries to count the leaves of root->right and root->left. But one of them is null. When it gets to that one, the program crashes because it's trying to access memory location 0.
Was This Post Helpful? 0
  • +
  • -

#17 #define  Icon User is offline

  • Duke of Err
  • member icon

Reputation: 1852
  • View blog
  • Posts: 6,661
  • Joined: 19-February 09

Re: Help with counting leaves in binary tree function

Posted 07 November 2017 - 03:10 PM

Are you struggling with recursion? It is not unusual, perhaps search online for a recursion tutorial in c++. eg.

7.11 Recursion


You are using root all the time and not using the nodePtr parameter, basically the function is not going anywhere.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2