BIG QUESTION... DESTRUCTOR ISSUE

Hi Everyone,

So I've finally gotten my code to work for the most part without any issue. I've used a bunch of Accessor methods to help with interacting with the "root". I think there is an issue with the Destructor. im not so sure it's even running. theoretically speaking, it should run and and delete the tree and then alert me that the tree has been deleted, any suggestions that would help via recursion??

The Code:

#include <iostream>

using namespace std;
struct Node
{
int data;
Node *left;
Node *right;

};

class treeClass
{

public:
treeClass(){root = NULL;};
void insertHelper(int);
void printHelper();
~treeClass();


private:
Node *root;
void insert(Node *&, int);
void print(Node *tree);
void destroy_tree(Node *&node);






};

int main()
{
treeClass tree1;
tree1.insertHelper(5);
tree1.insertHelper(3);
tree1.insertHelper(7);
tree1.printHelper();



system ("pause");
return 0;
}


void treeClass::insertHelper(int item)
{
insert(root, item);

}

void treeClass::insert(Node *&node, int item)
{
if(node == NULL)
{
node = new Node;
node->data = item;
node->left = NULL;
node->right = NULL;
return;
}
else if(node->data > item)
{
return insert(node->left, item);

}
else
{
return insert(node->right, item);
}



}

void treeClass::print(Node *tree)
{
if(tree != NULL)
{
print(tree->left);
cout << tree->data << " ";
print(tree->right);
}


}

void treeClass::printHelper()
{

if(root != NULL)
{

cout << "InOrder traversal : ";
print(root);
cout << endl;
}
else
cout << "This tree is Empty! " <<endl;
}

treeClass::~treeClass()
{
destroy_tree(root);
if(root == NULL)
cout << "The tree has beend delete....Goodbye!" << endl;

}
void treeClass::destroy_tree(Node *&node)
{
if(root!=NULL)
{
destroy_tree(node->left);
destroy_tree(node->right);
delete node;

}

}
delete will only release the memory, it will not set the pointer to NULL>
Last edited on
so i should set the root to NULL at the end of the destroy_tree()? As So:

void treeClass::destroy_tree(Node *&node)
{
if(root!=NULL)
{
destroy_tree(node->left);
destroy_tree(node->right);
delete node;

}
node = NULL;

}

when I try to run it now, the program crashed.
Nevermind, Thanks SO MUCH> I just realized the reason it just crash after is because I had "root" in the if statement smh, THANKS SO MUCH. I Set it to NULL and IT RUNS SMOOThLY!
Topic archived. No new replies allowed.