You are on page 1of 4

#include <stdio.h> #include <conio.h> #include <malloc.

h> struct node { int info; struct node *left,*right; } *root; void findbst(int x,struct node **location,struct node **parent) { struct node *ptr,*save; if(root==NULL) { *location=NULL; *parent=NULL; return; } if(x==root->info) { *location=root; *parent=NULL; return; } if(x<root->info) { ptr=root->left; save=root; } else { ptr=root->right; save=root; } while(ptr!=NULL) { if(x==ptr->info) { *parent=save; *location=ptr; return; } if(x<ptr->info) { save=ptr; ptr=ptr->left; } else { save=ptr; ptr=ptr->right; } } *location=NULL; *parent=save; return;

} void inserttree(int y) { struct node *loc,*par; findbst(y,&loc,&par); if(loc!=NULL) exit(1); struct node *temp; temp=(struct node *)malloc(sizeof(struct node)); temp->info=y; temp->left=NULL; temp->right=NULL; if(par==NULL) //insertion of root node { root=temp; } else { if(y<par->info) par->left=temp; else par->right=temp; } } void preorder(struct node *p) { struct node *q; q=p; if(p==NULL) return; printf("%d\t",q->info); preorder(q->left); preorder(q->right); } void inorder(struct node *p) { struct node *q; q=p; if(p==NULL) return; inorder(q->left); printf("%d\t",q->info); inorder(q->right); } void postorder(struct node *p) { struct node *q; q=p; if(p==NULL) return; postorder(q->left); postorder(q->right); printf("%d\t",q->info); }

struct data {int info; }; int main() { root=NULL; int t,ch,ans,i=0,j=0,A[10]; int ARR[]={15,10,19,18,22,25,2,11,1,7}; printf("Create the BST\n"); FILE *f; struct data d; f=fopen("init","w"); for(j=0;j<=9;j++) { d.info=ARR[j]; fwrite(&d,sizeof(struct data),1,f); } fclose(f); f=fopen("init","r"); for (i=0;i<10; i++) { fread(&d,sizeof(struct data),1,f); printf("%d\n",d.info); A[i]=d.info; } fclose(f); for(i=0;i<=9;i++) { inserttree(A[i]); } struct node *r; r=root; printf("\nTREE TRAVERSAL TYPE\n"); printf("\n1.)Preorder\n2.)Inorder\n3.)Postorder\n\n"); scanf("%d",&ch); switch(ch) { case 1: printf("The preorder traversal:\n"); preorder(r);getch(); break;

case 2: printf("The inorder traversal:\n"); inorder(r); getch(); break; case 3: printf("The postorder traversal:\n"); postorder(r); getch();break; } return 0; }

You might also like