So I created this Tree Class , whose object would be a generic tree. For the nodes of this Tree , I also created a TreeNode class and whose object would serve as the nodes of my Tree Object. However when I call delete on the object of my Tree Class , After deleting all the nodes , in the end it gives free() : invalid size on the outpput.Can anyone tell me what is wrong with my destructor? Should i just have one destructor? or is there any solution to this? Kindly consider me naive and ignore some small mistakes or let me know so that I can correct them.
#include <iostream>
#include <queue>
#include <vector>
using namespace std;
template <typename T>
class TreeNode{
public:
T data;
vector<TreeNode *> children;
TreeNode(T data){
this -> data = data;
}
~TreeNode(){
for(int i = 0 ; i < children.size() ; i++)
delete children[i];
}
};
template <typename T>
class Tree{
private:
TreeNode<T> *root;
public:
Tree(){
root = NULL;
}
~Tree(){
delete root;
}
void takeInput(){
cout<<"Enter root data"<<endl;
T rootData;
cin>>rootData;
TreeNode<T> *root = new TreeNode<T>(rootData);
queue<TreeNode<T> *> q;
q.push(root);
while(!q.empty()){
TreeNode<T> *front = q.front();
q.pop();
cout<<"Enter child data for "<<front -> data<<endl;
int childData;
cin>>childData;
while(childData != -1){
TreeNode<T> *child = new TreeNode<T>(childData);
front->children.push_back(child);
q.push(child);
cin>>childData;
}
}
this -> root = root;
}
void print(){
cout<<"Printing tree in level order form -: "<<endl;
queue<TreeNode<T> *> q;
q.push(root);
while(!q.empty()){
TreeNode<T> *front = q.front();
q.pop();
cout<<front -> data<<":";
for(int i = 0 ; i < front -> children.size() ; i++){
if(i == front -> children.size() - 1)
cout<<front->children[i]->data;
else
cout<<front -> children[i] -> data<<",";
q.push(front -> children[i]);
}
cout<<endl;
}
}
};
int main(){
Tree<int> t1;
t1.takeInput();
t1.print();
delete &t1;
}