/* TREE TRAVERSAL*/ #include #include #include<stdio.h> #include<process.h> class btree { struct node { node *lchild; int data; node *rchild; }*ptr; public: btree(); void insert(int); void traverse(void); void preorder(node *); void inorder(node *); void postorder(node *); }; btree :: btree() { ptr=NULL; } void btree :: insert(int n) { int found; node *p,*q,*r; p=new node; p->data=n; p->lchild=p->rchild=NULL; if(ptr==NULL) ptr=p; else { q=ptr; found=0; if(p->data < ptr->data) r=ptr->lchild; else { r=ptr->rchild; found=1; }
1
while(r!=NULL) { q=r; found=0; if(p->data < r->data) r=r->lchild; else { r=r->rchild; found=1; } } if(found==0) q->lchild=p; else q->rchild=p; } } void btree::preorder(node *t) { if(t!=NULL) { cout<<"\t"<data; preorder(t->lchild); preorder(t->rchild); } } void btree::inorder(node *t) { if(t!=NULL) { inorder(t->lchild); cout<<"\t"<data; inorder(t->rchild); } } void btree::postorder(node *t) { if(t!=NULL) { postorder(t->lchild); postorder(t->rchild); cout<<"\t"<data; } } void btree :: traverse(void)
2
{ char ch='y'; int choice; while(ch=='y') { cout<<"******** TREE TRAVERSAL *********\n"; cout<<"1. Preorder \t 2. Inorder \t 3. Postorder \t 4. Exit \n"; cout<<" Enter Choice:\n"; cin>>choice; switch(choice) { case 1: cout<<"Preorder Traversal:"; preorder(ptr); break; case 2: cout<<"Inorder Traversal:"; inorder(ptr); break; case 3: cout<<"Postorder Traversal:"; postorder(ptr); break; case 4: exit(0); break; default: cout<<"\n Wrong choice "; break; } cout<<"\n Do u want another traversal press 'y' else 'n'\n"; fflush(stdin); cin>>ch; } } int main() { btree bt; int i,num,n; cout<<"\n Enter No. of elements:\n"; cin>>num; for(i=0;i>n; bt.insert(n); } bt.traverse(); return 0; }
3