I am getting memory leaks specifcally when I am trying to a delete a node (as in when there are only insertion operations, there are no leaks) from my self balancing tree. After my delete and insertion operations are done, I call a function to destroy the tree, but there are still memory leaks. The function itself seems to be working fine (I print a pre order traversal of the tree after, and it is correct). This is what my delete function looks like:
node * Delete(node *T,int x)
{
node *p;
if(T==NULL)
{
return NULL;
}
else
if(x > T->data) // insert in right subtree
{
T->right=Delete(T->right,x);
if(BF(T)==2)
if(BF(T->left)>=0)
T=LL(T);
else
T=LR(T);
}
else
if(x<T->data)
{
T->left=Delete(T->left,x);
if(BF(T)==-2) //Rebalance during windup
if(BF(T->right)<=0)
T=RR(T);
else
T=RL(T);
}
else
{
//data to be deleted is found
if(T->right!=NULL)
{ //delete its inorder succesor
p=T->right;
while(p->left!= NULL)
p=p->left;
T->data=p->data;
T->right=Delete(T->right,p->data);
if(BF(T)==2)//Rebalance during windup
if(BF(T->left)>=0)
T=LL(T);
else
T=LR(T);\
}
else
return(T->left);
}
T->ht=height(T);
return(T);
}
And my destroy/ free function:
void destroytree (node* root)
{
if (root == NULL)
{
return;
}
destroytree(root->left);
destroytree(root->right);
printf("%d\n",root->key); // just to see what is happening.
free(root)
return;
}
I don't know how to free up the memory of the node that I am deleting. That is why there are memory leaks - when I print the root that is being freed(in destroytree), it is always the deleted node that is missing, therefore I think that's where memory leak is. My only problem is , with the deletenode function I've written I don't know where to free up this memory. I would appreciate any help. Also, I malloc in my insert node ofcourse, when I am inserting the node.