Monday, May 23, 2011

Write a program of Binary tree Traversal Tree After visiting the tree, students are required to traverse this tree in Pre-order, Post-order and in-order Traversal.

#include
struct dsa
{
struct dsa *leftchild;
int data;
struct dsa *rightchild;
};
void insert(struct dsa **,int);
void inorder(struct dsa *);
void preorder(struct dsa *);
void postorder(struct dsa *);

int main()
{
struct dsa *bt;
int req,i=1,num;
bt=NULL;
printf("enter the number of items to be inserted");
scanf("%d",&req);
while(i++<=req) { printf("enter the data"); scanf("%d",&num); insert(&bt,num); } printf("\n in order traversal"); inorder(bt); printf("\n pre order traversal"); preorder(bt); printf("\n postorder traversal"); postorder(bt); return 0; } void insert(struct dsa **sr,int num) { if (*sr==NULL) { *sr=malloc(sizeof(struct dsa)); (*sr)->leftchild=NULL;
(*sr)->rightchild=NULL;
(*sr)->data=num;
return;
}
else
{
if(num<(*sr)->data)
insert(&((*sr)->leftchild),num);
else
insert(&((*sr)->rightchild),num);
}
return;
}

void inorder(struct dsa *sr)
{
if(sr!=NULL)
{
inorder(sr->leftchild);
printf("\t%d",sr->data);
inorder(sr->rightchild);
}
else
return;
}

void preorder(struct dsa *sr)
{
if(sr!=NULL)
{
printf("\t%d",sr->data);
preorder(sr->leftchild);
preorder(sr->rightchild);
}
else
return;
}

void postorder(struct dsa *sr)
{
if(sr!=NULL)
{
postorder(sr->leftchild);
postorder(sr->rightchild);
printf("\t%d",sr->data);
}
else
return;
}


Output:

enter the number of items to be inserted5

enter the data1

enter the data2

enter the data3

enter the data4

enter the data5

in order traversal 1 2 3 4 5
pre order traversal 1 2 3 4 5
postorder traversal 5 4 3 2 1

No comments:

Post a Comment