#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
class NODE
{
public:
int data;
NODE *lc,*rc;
void create(NODE*);
void inorder(NODE*);
void preorder(NODE*);
void postorder(NODE*);
void push(NODE*);
int isempty();
NODE* pop();
};
NODE
*root,*nw,*temp,*st[10],*t;
int top=-1;
void
NODE::create(NODE *root)
{
char ch,ch1;
do
{
nw=new(NODE);
cout<<"Enter new
data:";
cin>>nw->data;
nw->lc=NULL;
nw->rc=NULL;
temp=root;
while(1)
{
cout<<"\nDo you
want to insert to the left/right of
"<<temp->data<<"?l/r:";
cin>>ch;
if(ch=='l'||ch=='L')
{
if(temp->lc==NULL)
{
temp->lc=nw;
break;
}
else
temp=temp->lc;
}
else
{
if(temp->rc==NULL)
{
temp->rc=nw;
break;
}
else
temp=temp->rc;
}
}
cout<<"Do you want to
continue?";
cin>>ch1;
}while(ch1=='y'||ch1=='Y');
}
void
NODE::inorder(NODE *root)
{
temp=root;
while(1)
{
while(temp!=NULL)
{
push(temp);
temp=temp->lc;
}
if(isempty())
break;
else
{
temp=pop();
cout<<temp->data;
temp=temp->rc;
}
}
}
void
NODE::preorder(NODE *root)
{
temp=root;
while(1)
{
while(temp!=NULL)
{
cout<<temp->data;
push(temp);
temp=temp->lc;
}
if(isempty())
break;
else
{
temp=pop();
temp=temp->rc;
}
}
}
void
NODE::postorder(NODE *root)
{
temp=root;
while(1)
{
while(temp!=NULL)
{
push(temp);
temp=temp->lc;
}
while(st[top]->rc==temp&&top!=-1)
{
temp=pop();
cout<<temp->data;
}
if(isempty())
break;
temp=st[top]->rc;
}
}
int
NODE::isempty()
{
if(top==-1)
return(1);
else
return(0);
}
void
NODE::push(NODE *t)
{
top++;
st[top]=t;
}
NODE *NODE::pop()
{
t=st[top];
top--;
return(t);
}
void main()
{
int sw;
NODE a;
clrscr();
do
{
cout<<"\n\tMenu\n1.Create
root\n2.Inorder\n3.Preorder\n4.Postorder\n5.Exit\nEnter Choice:";
cin>>sw;
switch(sw)
{
case 1:
root=new(NODE);
root->lc=NULL;
root->rc=NULL;
cout<<"\nEnter
root data:";
cin>>root->data;
a.create(root);
break;
case 2:
a.inorder(root);
break;
case 3:
a.preorder(root);
break;
case 4:
a.postorder(root);
break;
case 5:
exit(0);
break;
default:
cout<<"\nEnter
correct choice";
break;
}
}while(sw<5);
}
/*
Output:-
Menu
1.Create root
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter Choice:1
Enter root data:1
Enter new data:2
Do you want to
insert to the left/right of 1?l/r:l
Do you want to
continue?y
Enter new data:3
Do you want to
insert to the left/right of 1?l/r:l
Do you want to
insert to the left/right of 2?l/r:l
Do you want to
continue?y
Enter new data:4
Do you want to
insert to the left/right of 1?l/r:r
Do you want to
continue?n
Menu
1.Create root
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter Choice:2
3214
Menu
1.Create root
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter Choice:3
1234
Menu
1.Create root
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter Choice:4
3241
Menu
1.Create root
2.Inorder
3.Preorder
4.Postorder
5.Exit
Enter Choice:5