Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary Search Tree Destructor

Working on implementing my own BST in C++ for the experience of dealing with such structures.

I've had trouble implementing a destructor. I found in my studies, that one can't really have a recursive destructor (due to a flag that doesn't allow the destructor to be called on the same object after having been called), but I'm not really sure of any other way to successfully clean up all the nodes in the tree.

To compensate, I've created a helper function - however this throws an unresolved external error on the 'delete n' line. Any tips?

Code:

void BinSearchTree::Clear(tNode* n)
{
    if (n->left != NULL)
        Clear(n->left);
    if (n->right != NULL)
        Clear(n->right);
    delete n;
    n = NULL;
    size--;
}
like image 395
DivinusVox Avatar asked Nov 05 '11 06:11

DivinusVox


1 Answers

You can have a recursive destructor; what you can't do is delete the same object twice.

A typical way to delete a tree in C++ might be something like this:

BinSearchTree::~BinSearchTree()
{
   delete _rootNode;  // will recursively delete all nodes below it as well
}

tNode::~tNode()
{
   delete left;
   delete right;
}

Regarding the unresolved external error -- is that error thrown when you try to compile/link the program? If so, it's probably because the code for the tNode class (and in particular the tNode destructor, if you declared one) doesn't exist or isn't getting compiled into your project.

like image 188
Jeremy Friesner Avatar answered Oct 14 '22 13:10

Jeremy Friesner