I wrote a function to delete a node in the binary search tree. The code works well in case of node having no child but fails when the node has one or two child.
Code:
void deleteNode(bstree **rootref,int delnum)
{
bstree *temp,*parent,*succ;
if(search(*rootref,delnum)==0)
printf("Deletion denied, entered number not in the tree\n");
temp=*rootref;
while(temp&&((temp->data)!=delnum))
{
parent=temp;
if(temp->data<delnum) temp=temp->right;
else temp=temp->left;
}
if(!temp) printf("the element not present,deletion denied\n");
if(!(temp->left)&&!(temp->right))
{
if(parent->left==temp) parent->left=NULL;
else parent->right=NULL;
}
else if((temp->left)&&!(temp->right))
{
if(parent->left=temp) parent->left=temp->left;
else parent->right=temp->left;
}
else if((temp->right)&&!(temp->left))
{
if(parent->left=temp) parent->left=temp->right;
else parent->right=temp->right;
}
else
{
succ=temp->right;
while(succ->left) succ=succ->left;
temp->data=succ->data;
temp=succ;
}
free(temp);
}