#include<iostream.h>
#include<conio.h>
class tree
{
public:
char info;
tree *lchild;
tree *rchild;
};
class treetraversal
{
private:
char x;
public:
void input(tree *p);
void preorder(tree *p);
void inorder(tree *p);
void postorder(tree *p);
};
void treetraversal::input(tree *ptr)
{
cout<<"\n\tEnter the element:";
cin>>x;
if(x=='0')
ptr->info='$';
else
{
ptr->info=x;
cout<<"\n\t"<<ptr->info<<"Left is:\n"<<endl;
ptr->lchild=new tree;
input(ptr->lchild);
cout<<"\n\t"<<ptr->info<<"Right is :\n"<<endl;
ptr->rchild=new tree;
input(ptr->rchild);
}
}
void treetraversal::preorder(tree *ptr)
{
if(ptr->info!='$')
{
cout<<ptr->info;
preorder(ptr->lchild);
preorder(ptr->rchild);
}
}
void treetraversal::inorder(tree *ptr)
{
if(ptr->info!='$')
{
inorder(ptr->lchild);
cout<<ptr->info;
inorder(ptr->rchild);
}
}
void treetraversal::postorder(tree *ptr)
{
if(ptr->info!='$')
{
postorder(ptr->lchild);
postorder(ptr->rchild);
cout<<ptr->info;
}
}
void main()
{
treetraversal t;
tree *te=new tree;
clrscr();
t.input(te);
cout<<"\n\tThe Pre-order traversal for the given tree is:";
t.preorder(te);
cout<<"\n\tThe In-order traversal for the given tree is:";
t.inorder(te);
cout<<"\n\tThe Post-order traversal for the given tree is:";
t.postorder(te);
getch();
}
No comments:
Post a Comment