#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int info;
struct node *left,*right;
}NODE,*NODEPTR;
NODEPTR getnode()
{
NODEPTR temp=(NODEPTR)malloc(sizeof(NODE));
temp->left=temp->right=NULL;
return temp;
}
NODEPTR create(NODEPTR root,int item)
{
NODEPTR temp,cur,prev;
temp=getnode();
temp->info=item;
if(root==NULL)
return temp;
cur=root;
prev=NULL;
while(cur!=NULL)
{
prev=cur;
if(cur->info > item)
cur=cur->left;
else
cur=cur->right;
}
if(item < prev->info)
prev->left=temp;
else
prev->right=temp;
return root;
}
void inorder(NODEPTR root)
{
if(root!=NULL)
{
inorder(root->left);
printf("%d\t",root->info);
inorder(root->right);
}
}
void preorder(NODEPTR root)
{
if(root!=NULL)
{
printf("%d\t",root->info);
preorder(root->left);
preorder(root->right);
}
}
void postorder(NODEPTR root)
{
if(root!=NULL)
{
postorder(root->left);
postorder(root->right);
printf("%d\t",root->info);
}
}
main()
{
NODEPTR root=NULL;
int item,ch,cont=1;
printf("Enter elements and -1 to terminate\n");
while(1)
{
scanf("%d",&item);
if(item==-1)break;
root=create(root,item);
}
while(cont==1)
{
printf("1.Inorder 2.Preorder 3.Postorder \n");
scanf("%d",&ch);
switch(ch)
{
case 1 : inorder(root);
break;
case 2 : preorder(root);break;
case 3 : postorder(root);break;
default : return;
}
}
}
No comments:
Post a Comment