binary tree destructor

I'm trying to make my destructor which will free up my entire binary tree. From my research online, it seems like a lot of people use recursion, but I just cannot seem to get this to work. It seg faults like mad, and I have no idea what the cause is. One of the errors I'm getting is a double free (deleting the same node twice), but I only ever call the destructor once.

This destructor is being used within a huffman tree (hence why the class is called Huffman). What I'm trying to do is delete the node, and then set the pointer within the parent node to null so that it won't be called again by recursion (at least I think that's how it works?)

Can anyone provide some insight? Me and a friend worked on this for about 2 hours tonight and we couldn't make any headway.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
Huffman :: ~Huffman()
{
	destroy(root);
}

void Huffman :: destroy(BTree* node)
{		
	if (node != NULL)
	{
		BTree *parent; 
		
		if (node->getParent() != NULL)
		{
			parent = node->getParent();
		}
		
		if (node->getLeftChild() != NULL)
		{
		    destroy(node->getLeftChild());
		    if(parent != NULL)
		    	parent->setLeft(NULL);
		}
		else if (node->getRightChild() != NULL)
		{
		    destroy(node->getRightChild());
		    if (parent != NULL)
		    	parent->setRight(NULL);
		}
		
		delete node;
		node = NULL;
	}
}
You do not need to handle parent. It will be already handled by previous calls to destroy(). As long as BTree destructor will not cause any furnther calls, following should work.
1
2
3
4
5
6
7
8
9
10
void Huffman :: destroy(BTree* node)
{		
    if (node != NULL)	{
        destroy(node->getLeftChild());
        node->setLeft(NULL);
        destroy(node->getRightChild());
        node->setLeft(NULL);
	delete node;
    }
}
Topic archived. No new replies allowed.