Sei sulla pagina 1di 4

#include<iostream>

//#include<conio.h>
#define max 20
using namespace std;
int cnt=0;

class bt
{
private:
char data;
bt *lchild,*rchild;
public:
void create();
void insert(bt *root,bt *next);
void inorder(bt *root);
void preorder(bt *root);
void postorder(bt*root);
};
bt *root,*stk[max];

void bt::create()
{
bt *next;
int ch1;
root=new bt;
cout<<"\n\nEnter the data::";
cin>>root->data;
root->lchild=root->rchild=NULL;
cnt++;
do
{
cout<<"\n\nWant to add more?(1/0):";
cin>>ch1;
if(ch1==1)
{
next=new bt;
cout<<"\n\nEnter the data for new root:";
cin>>next->data;
next->lchild=next->rchild=NULL;
insert(root,next);
}
}while(ch1==1);
}

void bt::insert(bt *root,bt *next)


{
char chr;
bt *temp;
cout<<"\n\nData has to be inserted\t"<<root->data<<" 'L' or'R':\t";
cout<<"\nEnter your choise\n";
cin>>chr;
if(chr=='l'||chr=='L')
{
if(root->lchild==NULL)
{
root->lchild=next;
cnt++;
}
else
{
insert(root->lchild,next);
}
}
if(chr=='r'||chr=='R')
{
if(root->rchild==NULL)
{
root->rchild=next;
cnt++;
}
else
{
insert(root->rchild,next);
}
}
}

void bt::inorder(bt *root)


{
int top=-1;
bt *temp;
temp=root;
if(root!=NULL )
{
do
{
while(temp!=NULL)
{
top++;
stk[top]=temp;
temp=temp->lchild;
}
if(top!=-1)
{
temp=stk[top];
cout<<" "<<temp->data;
temp=temp->rchild;
top--;
}
}while(temp!=NULL || top!=-1);
}
}

void bt::preorder(bt *root)


{
int top=-1;
bt *temp;
temp=root;
if(root!=NULL && cnt>0 )
{
do
{
while(temp!=NULL)
{
top++;
stk[top]=temp;
cout<<" "<<temp->data;
temp=temp->lchild;
}
if(top!=-1)
{
temp=stk[top];
temp=temp->rchild;
top--;
}
}while(temp!=NULL||top!=-1);
}
if(cnt==0)
cout<<"\nEmpty tree:";
}

void bt::postorder(bt *root)


{
int top=-1;
bt *temp;
char arr[max];
int i,j;
i=0;
temp=root;
if(root!=NULL )
{
do
{
while(temp!=NULL)
{
arr[i]=temp->data;
i++;
top++;
stk[top]=temp;
temp=temp->rchild;
}
if(top!=-1)
{
temp=stk[top];
temp=temp->lchild;
top--;
}
}while(temp!=NULL||top!=-1);
for(j=i-1;j>=0;j--)
{
cout<<" "<<arr[j];
}
}
}
int main()
{ cout<<"\n\t\tOUTPUT FOR NON-RECURSIVE TRAVERSAL";
int c;
bt s;

do
{
cout<<"\n\n1:Create\n\n2:Inorder\n\n3:Preorder\n\n4:Postorder\
\n\n5:Exit";
cout<<"\n\nEnter your choice::";
cin>>c;
switch(c)
{
case 1:
s.create();
break;
case 2:
s.inorder(root);
break;
case 3:
s.preorder(root);
break;
case 4:
s.postorder(root);
break;
case 5:
break;
default:
cout<<"\nError in giving option,try again.\n";
}
}while(c!=5);
}

Potrebbero piacerti anche