// BINARY SEARCH TREE INSERTION, TRAVERSALS
struct node
{
int info;
struct node *left,*right;
};
struct node *root;
void insert(struct node *tree,int number)
{
struct node *p,*q,*temp;
p=q=tree;
if(tree==NULL)
{
temp=(struct node*)malloc(sizeof(struct node));
temp->info=number;
temp->left=temp->right=NULL;
root=temp;
}
else
{
while(number !=p->info && q!=NULL)
{
p=q;
if(number <>info )
q=p->left;
else
q=p->right;
}
if(number==p->info)
printf("\n DUPLICATE ");
else
{
temp=(struct node*)malloc(sizeof(struct node));
temp->info=number;
temp->left=temp->right=NULL;
if(number <>info)
p->left=temp;
else
p->right=temp;
}
}
}
void postorder(struct node *p)
{
if(p!=NULL)
{
postorder(p->left);
postorder(p->right);
printf("\t\t%d",p->info);
}
}
void inorder(struct node *p)
{
if(p!=NULL)
{
inorder(p->left);
printf("\t\t%d",p->info);
inorder(p->right);
}
}
void preorder(struct node *p)
{
if(p!=NULL)
{
printf("\t\t%d",p->info);
preorder(p->left);
preorder(p->right);
}
}
void main()
{
int el,l,v;
int c;
root=NULL;
while(1)
{
printf("\n1.insert\n 2.preorder\n3.inorder");
printf("\n4.postorder\n5.exit\n");
printf("\n Enter U r choice\n"); scanf("%d",&c);
switch(c)
{
case 1:
printf("\n Enter Element to insert");
scanf("%d",&v);
insert(root,v);
break;
case 2:
preorder(root);break;
case 3:
inorder(root);break;
case 4:
postorder(root);break;
case 5:
exit(0);
}
}
}
Tuesday, April 7, 2009
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment