Delete Tree not working

I have the following code in my class to delete the entire tree.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
void Tree::makeEmpty()
{
	clear(root);
}

void Tree::clear(Node* current)
{
	if(current != NULL)
	{
		clear(current->left);
		clear(current->right);
		if(current->left == NULL && current->right == NULL)
		{
			delete current;
			current = NULL;
		}
	}
}


Later in the class, I defined a function that turns the tree into an array (which works) and also deletes the tree. I delete the tree by calling the makeEmpty function. I created a main, and to test to see if the tree is really deleted, I try to cout my tree, which has currently been overloaded so couting the tree just prints out the data of the node that root is pointing too.

1
2
3
4
5
ostream& operator<<(ostream &out, const Tree &tree)
{
	out << *tree.root->data;
	return out;
}


When I try to cout my tree (which I assume to be deleted because I called my makeEmpty function), it actually prints out the value which was at the root, which leads me to believe the tree was not deleted at all. Can anyone tell me why that is?
When I try to cout my tree


Don't. Doing so results in undefined behavior.

You might find the following an interesting read. Although the question is about a slightly different situation, the principle is the same.

http://stackoverflow.com/a/6445794
The reason I cout it is because there's another function that I'm calling that typically goes through the tree's nodes and prints out its data. The first line of that function is if(current != NULL). The tree is empty, but when I debugged it, it gets past this line just fine. Therefore, my tree is not deleting properly because it's not reading the root as null.

Also, I do have to overload the cout for this class eventually as it is part of the assignment.
Line 15 is not doing what you think it does because you have line 6 wrong.
Topic archived. No new replies allowed.