Tree Traversal
Tree Traversal
(BST).
#include<stdio.h>
#include<conio.h>
struct node
{
int info;
struct node *lchild;
struct node *rchild;
}*root;
void postorder(struct node *);
void preorder(struct node *);
void inorder(struct node *);
void insert(int);
void del(int);
void display(struct node *,int);
void case_a(struct node *,struct node *);
void case_b(struct node *,struct node *);
void case_c(struct node *,struct node *);
void main()
{
int ch,num;
char z;
clrscr();
while(1)
{
clrscr();
printf("\n\t **********MENU************ ");
printf("\n\t 1.Insert.");
printf("\n\t 2.Delete.");
printf("\n\t 3.Inorder Traversal.");
printf("\n\t 4.Preorder Traversal.");
printf("\n\t 5.Postorder Traversal.");
printf("\n\t 6.Display.");
printf("\n\t 7.Exit.");
printf("\n\t Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\n\t Enter the number to be inserted:");
scanf("%d",&num);
insert(num);
break;
case 2:
printf("\n\t Enter the number to be deleted : ");
scanf("%d",&num);
del(num);
break;
case 3:
inorder(root);
break;
case 4:
preorder(root);
break;
case 5:
postorder(root);
break;
case 6:
display(root,1);
break;
case 7:
exit(0);
default:
printf("\n\t Wrong choice\n");
}
printf("\n\t Do u want to continue:");
fflush(stdin);
scanf("%c",&z);
}
getch();
}
while(ptr!=NULL)
{
if(item==ptr->info)
{ *loc=ptr;
*par=ptrsave;
//return;
}
ptrsave=ptr;
if(item<ptr->info)
ptr=ptr->lchild;
else
ptr=ptr->rchild;
}/*End of while */
*loc=NULL; /*item not found*/
*par=ptrsave;
}/*End of find()*/
if(parent==NULL)
root=tmp;
else
if(item<parent->info)
parent->lchild=tmp;
else
parent->rchild=tmp;
}/*End of insert()*/
void del(int item)
{
struct node *parent,*location;
if(root==NULL)
{
printf("\n\t Tree empty");
return;
}
find(item,&parent,&location);
if(location==NULL)
{
printf("\n\t Item not present in tree");
return;
}
/*Initialize child*/
if(loc->lchild!=NULL) /*item to be deleted has lchild */
child=loc->lchild;
else /*item to be deleted has rchild */
child=loc->rchild;
suc->lchild=loc->lchild;
suc->rchild=loc->rchild;
}/*End of case_c()*/