#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
struct node
{struct node * left;
struct node * right;
int info;
};
typedef struct node node;
node * root=NULL,*loc,*par,*save,*child;
int item;
void pre(node *);
void in(node *);
void post(node *);
void find()
{
node * ptr;
loc=root;
par=NULL;
if(root==NULL)
{
loc=NULL;
par=NULL;
return;
}
if(root->info==item)
{
loc=root;
par=NULL;
}
if(item<root->info)
{
ptr=root->left;
save=root;
}
else
{
ptr=root->right;
save=root;
}
while(ptr!=NULL)
{if(item==ptr->info)
{
loc=ptr;
ptr=save;return;
}
if(item<root->info)
{save=ptr;ptr=ptr->left;}
else
{save=ptr;ptr=ptr->right;
}
}
loc=NULL;par=save;
}
void create()
{
node * new1;
printf("enter item");
scanf("%d",&item);
find();
if(loc!=NULL)
printf("node already present\n");
else
{
new1=(node*)malloc(sizeof(node*));
new1->info=item;
new1->left=NULL;
new1->right=NULL;
if(par==NULL)
{ root=new1;
}
else
{if(item<par->info)
par->left=new1;
else
par->right=new1;
}
}
}
void del1()
{
if(loc->left==NULL&&loc->right==NULL)
{child=NULL;}
else if(loc->left!=NULL)
child=loc->left;
else
child=loc->right;
if(par!=NULL)
{
if(loc==par->left)
par->left=child;
else
par->right=child;
}
else root=child;
}
void del()
{
printf("enter item to be deleted");
scanf("%d",&item);
find();
if(loc==NULL)
{
printf("not present ");return;}
if(loc->right!=NULL&&loc->left!=NULL)
return;
else
{
del1();
printf("here in del1");
}
}
void pre(node * temp)
{
if(temp==NULL)
return;
printf("%d\t",temp->info);
pre(temp->left);
pre(temp->right);
}
void in(node * temp)
{
if(temp==NULL)
return;
in(temp->left);
printf("%d\t",temp->info);
in(temp->right);
}
void post(node * temp)
{
if(temp==NULL)
return;
post(temp->left);
post(temp->right);
printf("%d\t",temp->info);
}
int main()
{int ch=1;
do{
printf("\nMENU......\n");
printf("1)Add nodes\n");
printf("2)Preorder\n");
printf("3)Inorder\n");
printf("4)Postorder\n");
printf("5)Delete\n");
printf("enter choice");
scanf("%d",&ch);
switch(ch)
{
case 1:create();break;
case 2:pre(root);break;
case 3:in(root);break;
case 4:post(root);break;
case 5:del();break;
default:return 0;
}
printf("do you want to continue1/0\n");
scanf("%d",&ch);
}while(ch!=0);
getch();
return 0;
}
I am running this program in Bloodshed Dev C++.
When I run it in normal execution,all the entries of the tree become 2 .
However,in Debug Mode insertion and traversal work fine.
I am not able to understand this........
del1() deletes a node if present and has only 0 or 1 children.
But del1() is deleting the whole tree in my case....
Any help will be appreciated.
PS:I am a Beginner