You are on page 1of 3

PROGRAM 10: TRAVERSING A TREE IN PRE,IN AND POST ORDER MANNER

#include<stdio.h> #include<conio.h> #include<stdlib.h> typedef struct TREE { int i; struct TREE *left,*right; }tree; int insert(tree **,int i); int in(tree*); int pre(tree*); int post(tree*); int main() { tree *head=NULL; printf("enter the no.s to insert\n"); int i,j; for(i=0;i<2;i++) { scanf("%d",&j); insert(&head,j); } printf("\nPre order\n"); pre(head); printf("\nPost order\n"); post(head);

printf("\nIn order\n"); in(head); getch(); return 0; } int insert(tree** head,int i) { tree *temp1; temp1=*head; if(*head==NULL) { tree* temp=(tree*)malloc(sizeof(tree)); *head=temp; (*head)->i=i; temp->right=NULL; temp->left=NULL; return 0; } while(*head!=NULL) { if(i>((*head)->i)) insert(&(temp1->right),i); else if(((*head)->i)>i) insert(&(temp1->left),i); } return 0; }

int pre(tree* head) { if(head==NULL) return 0; printf("%d ",head->i); pre(head->left); pre(head->right); return 0; } int post(tree* head) { if(head==NULL) return 0; post(head->left); post(head->right); printf("%d ",head->i); return 0; } int in(tree* head) { if(head==NULL) return 0; in(head->left); printf("%d ",head->i); in(head->right); return 0; }

You might also like