When destroying(when objects is out of scope) General Tree is it necessary to traverse each node and deleting them like you do with doubly linked list? The General Tree I am writing is a circular so that insertion can be done in constant time. It would be much helpful if someone could help me fix the error. The destructor below currently causes stack overflow( I think it is because of the tree being circular).
Here are the 2 destructors
~Node()
{
if(left){delete left;}
if(next){delete next;}
if(parent){delete parent;}
}
for General tree
~Gen()
{
if (head)
delete head; //call destructor on node
head = nullptr;
m_size = 0;
}
This is the node class
class Node {
public:
typedef Node* nodePtr;
int data;
//Left child- right sibling implementation
nodePtr left, next, parent;
int rank; //will be used for merging.
~Node()
{
if(left){delete left;}
if(next){delete next;}
if(parent){delete parent;}
}
private:
Node & operator =(const Node&);
};
this is the tree that uses the node above
class Gen{
public:
typedef Node* nodePtr;
Gen():m_size(0),head(0){}
~Gen()
{
if (head)
delete head; //call destructor on node
head = nullptr;
m_size = 0;
}
void push(int val)
{
nodePtr newNode = new Node;
newNode->data = val;
newNode->rank = 0;
newNode->left = newNode->next = newNode->parent = 0; //set all pointers to null
insertRoot(newNode); //call the inserthelper
++m_size;
}
//other functions (deleteMin, decreaseKey etc)
private:
int m_size;
nodePtr head;
nodePtr insertRoot(nodePtr newNode)
{
//create a circular link
if (!head)
{
head = newNode;
newNode->next = newNode;
}
else
{
newNode->next = head->next;
head->next = newNode;
if (newNode->data < head->data) //min heap (lazy insert)
head = newNode;
}
}
};