#include<iostream.h>
class node
{
node *lchild;
node *rchild;
char data;
public:
node()
{
lchild=rchild=NULL;
data='0';
}
void getdata()
{
cout<<"\nEnter the data: ";
cin>>data;
}
friend class tree;
};
class tree
{
node *root;
public:
tree()
{
root=new node();
cout<<"\nCREATE BINARY TREE \n";
cout<<"\n================== \n";
create(root);
}
void create(node *nnode)
{
char ch;
nnode->getdata();
cout<<"\tIs there a left child(y/n)"<<nnode->data<<"\t";
cin>>ch;
if(ch=='Y'||ch=='y')
{
nnode->lchild=new node;
create(nnode->lchild);
}
cout<<"\tIs there a right child(y/n)"<<nnode->data<<"\t";
cin>>ch;
if(ch=='Y'||ch=='y')
{
nnode->rchild=new node;
create(nnode->rchild);
}
}
void inorder(node *node)
{
if(node!=NULL)
{
inorder(node->lchild);
cout<<node->data;
inorder(node->rchild);
}
}
void preorder(node *node)
{
if(node!=NULL)
{
cout<<node->data;
preorder(node->lchild);
preorder(node->rchild);
}
}
void postorder(node *node)
{
if(node!=NULL)
{
preorder(node->lchild);
preorder(node->rchild);
cout<<node->data;
}
}
void display(int order)
{
if(order==1)
{
cout<<"\n\t INORDER TRAVESAL\n";
cout<<"-------------------------------\n\n\t\t";
inorder(root);
}
else if(order==2)
{
cout<<"\n\tPreorder traversal\n";
preorder(root);
}
else if(order==3)
{
cout<<"\n\tPostorder traversal\n";
postorder(root);
}
}
};
main()
{
int choice;
tree t;
do
{
cout<<"\n\n\n1.INORDER TRAVESAL\n";
cout<<"\n2.PREORDER TRAVESAL\n";
cout<<"\n3.POSTORDER TRAVESAL\n";
cout<<"\n4.EXIT\n";
cout<<"\nEnter your choice ::";
cin>>choice;
if(choice>0 && choice<5)
{
t.display(choice);
}
else
{
cout<<"\nInvalid choice";
cout<<"\nPress any key to continue";
}
}while(choice>0 && choice<4);
}
0 comments:
Post a Comment