You are on page 1of 4

EXP 11 AIM: Traversing the elements of a Tree #include<conio.h> #include<iostream.h> #include<stdio.

h> struct node { int num; struct node*left; struct node*right; }; typedef struct node node; node *root = NULL; node *insert(node *tree , long num ); void preorder (node *tree); void inorder (node *tree); void postorder (node *tree); int count,i,s,c = 1; int select(); void main() { int choice; long digit; clrscr(); do { choice = select(); switch (choice) { case 1 : puts("Enter elements: To quit enter 0 "); cin>>digit; c=digit; while(c!=0) { root = insert (root, digit); cin>>digit;

c=digit; }; continue ; case 2 : puts (" Preorder traversing TREE "); preorder(root) ; cout<<endl; continue ; case 3 : puts (" Inorder traversing TREE "); inorder(root) ; cout<<endl; continue ; case 4 : puts (" Preorder traversing TREE "); postorder(root) ; cout<<endl; continue ; case 5 : puts ("END "); exit(0); } }while(choice != 5); } int select() { int selection; do { puts ("Enter 1 : Insert a node in Tree "); puts ("Enter 2 : Display (preorder) the Tree "); puts ("Enter 3 : Display (inorder) the Tree "); puts ("Enter 4 : Display (postorder) the Tree "); puts ("Enter 5 : END"); puts ("Enter your choice"); cin>>selection; if(( selection <1) || (selection >5)) { puts ("Wrong choice : Try again "); getch(); } }while ((selection <1)|| (selection >5)); return( selection); }

node *insert(node*P , long digit ) { if (P==NULL) { P=(node*)malloc(sizeof(node)); P->left= P->right=NULL; P->num=digit; count++; } else if(count%2 == 0) P->left = insert (P->left,digit); else P->right= insert (P->right,digit); return(P); } void preorder (node *P) { if(P!=NULL) { cout<< P->num; preorder(P->left); preorder(P->right); } } void inorder(node *P) { if (P!=NULL) { inorder (P->left); cout<<P->num; inorder (P->right); } } void postorder (node *P) { if(P!=NULL) { preorder(P->left);

preorder(P->right); cout<<P->num; } }

OUTPUT:

You might also like