//Name: Pratik n Patel //Roll No: 02CE048 //Program to create a binary tree and traverse it. #include #include #include struct node { int data; struct node *lptr; struct node *rptr; }; #define link struct node void pre_order(link *); void post_order(link *); void in_order(link *); void main() { clrscr(); int dat[10]; printf("Enter ten different integers:"); for(int i=0;i<10;i++) { scanf("%d",&dat[i]); } link *head; link *temp; link *root; head = (link *) malloc (sizeof(link)); head->data=dat[0]; head->lptr=head->rptr=NULL; for(i=1;i<10;i++) { temp=head; start: if(dat[i]data&&temp->lptr==NULL) { temp->lptr = (link *) malloc (sizeof(link)); temp=temp->lptr; temp->data=dat[i]; temp->lptr=temp->rptr=NULL; continue; } else if(dat[i]data&&temp->lptr!=NULL) { temp=temp->lptr; goto start; } else if(dat[i]>temp->data&&temp->rptr==NULL) { temp->rptr = (link *) malloc (sizeof(link)); temp=temp->rptr; temp->data=dat[i]; temp->lptr=temp->rptr=NULL; } else if(dat[i]>temp->data&&temp->rptr!=NULL) { temp=temp->rptr; goto start; } } printf("\nBinary tree created..."); getch(); start2: clrscr(); printf("\n\n1.Pre Order\n2.Post Order\n3.In Order\nEnter your choice:"); int choice; scanf("%d",&choice); switch(choice) { case 1: { root=head; pre_order(root); getch(); } break; case 2: { root=head; post_order(root); getch(); } break; case 3: { root=head; in_order(root); getch(); } break; default: { printf("Enter a valid choice.."); getch(); goto start2; } break; } } void pre_order(link *root1) { link *root; printf("%d ",root1->data); if(root1->lptr!=NULL) { root=root1->lptr; pre_order(root); } if(root1->rptr!=NULL) { root=root1->rptr; pre_order(root); } } void post_order(link *root1) { link *root; if(root1->lptr!=NULL) { root=root1->lptr; post_order(root); } if(root1->rptr!=NULL) { root=root1->rptr; post_order(root); } printf("%d ",root1->data); } void in_order(link *root1) { link *root; if(root1->lptr!=NULL) { root=root1->lptr; in_order(root); } printf("%d ",root1->data); if(root1->rptr!=NULL) { root=root1->rptr; in_order(root); } } /*------------------------------------------------------ output -------------------------------------------------------- Enter ten different integers:12 54 542 213 1231 5848 12247 212 32 8 Binary tree created... 1.Pre Order 2.Post Order 3.In Order Enter your choice:3 8 12 32 54 212 213 542 1231 5848 12247 */