struct node
{ int data;
struct node* left;
struct node* right;};
int Getheight(struct node* root)
{
if(root==NULL)
{
return -1;
}
if(root->left==NULL && root->right==NULL)
{
return 0;
}
else if(root->left!=NULL && root->right==NULL)
{
return root->left->height+1;
}
else if(root->left==NULL && root->right!=NULL)
{
return root->right->height+1;
}
else if(root->left->height>=root->right->height)
{
return root->left->height+1;
}
return root->right->height+1;
}
int Getbalance(struct node* x)
{
return Getheight(x->left)-Getheight(x->right);
}
struct node* FindMin(struct node* root)
{ if(root==NULL)
{
return root;
}
else if(root->left==NULL)
{
return root;
}
else
{
return FindMin(root->left);
}
}
struct node* Delete(struct node* root,int data)
{
if(root->data==data)
{
if(root->left==NULL || root->right==NULL)
{
struct node* temp=root->left?root->left:root->right;
if(temp==NULL)
{
temp=root;
free(temp)
root=NULL;
}
else
{
*root=*temp;
free(temp);
}
}
else
{
struct node* temp=FindMin(root->right);
root->data=temp->data;
root->right=Delete(root->right,root->data);
}
if(root!=NULL)
{
root->height=Getheight(root);
int bf=Getbalance(root);
if(bf>1 && data<root->data)
{
root=rightrotate(root);
}
if(bf<-1 && data>root->data)
{
root=leftrotate(root);
}
if(bf>1 && data>root->data)
{
root->left=leftrotate(root->left);
root=rightrotate(root);
}
if(bf<-1 && data<root->data)
{
root->right=rightrotate(root->right);
root=leftrotate(root);
}
}
return root;
}
else if(root==NULL)
{
printf("FALSE");
printf("\n");
return root;
}
else if(data>root->data)
{
root->right=Delete(root->right,data);
}
else if(data<root->data)
{
root->left=Delete(root->left,data);
}
}
int main()
{ struct node* root=NULL;
int data;
char c='j';
while(c!='e')
{
scanf(" %c",&c);
if(c=='i')
{
scanf(" %d",&data);
root=Insert(root,data);
}
else if(c=='p')
{
preorder(root);
printf("\n");
}
else if(c=='s')
{
scanf(" %d",&data);
Search(root,data);
}
else if(c=='b')
{
scanf(" %d",&data);
Balance(root,data);
}
else if(c=='d')
{
scanf(" %d",&data);
printf("%d",data);
printf("\n");
root=Delete(root,data);
}
}
}
The input/output I get are
i 4 //i is insert operation
i 6
i 3
i 2
i 1
s 2 //s is search returns true and false
TRUE//output for above search
p //preorder traversal:3 () ()=>node with data 3 has left child NULL and right child
NULL
( 4 ( 2 ( 1 ( ) ( ) ) ( 3 ( ) ( ) ) ) ( 6 ( ) ( ) ) )
b 4 //b returns balanceheight of the node containing data=4
1 //output to b
d 3 // delete
3
p
( )
When i debug the program with these inputs,it always stops in delete(d 3) function with the unknown stopping event occurred at free function.Can anyone help me understand what the problem is??The function for search,insert,balance works perfectly.I am unable to post reat of the code in the question.The problem occurs with the delete function.