Search This Blog

Saturday, 10 November 2012

Binary tree traversals (in-order,pre-order and post-order) using linked list

#include<iostream.h>
#include<conio.h>
struct node
{
node*left,*right;
int data;
};
class tree
{
node *start;
public:
tree()
{
start=NULL;
}
void search(int,int&,node*&);
void insert(int);
void traversal();
void in(node*);
void pre(node*);
void post(node*);
};
void tree::search(int n,int&found,node*&parent)
{
node*q;
q=start;
if(q==NULL){
parent=NULL;
}
else

{
while(q!=NULL){
if(q->data==NULL){
found=1;
break;
}
else if(n>q->data)
{
parent=q;
q=q->right;
}
else
{
parent=q;
q=q->left;
}}}
}
void tree::insert(int n)
{
node *parent,*t;
int found=0;
search(n,found,parent);
if(found==1)
cout<<"Duplicate";
else
{
t=new node;
t->data=n;
t->left=NULL;
t->right=NULL;
if(parent==NULL)
{
start=t;
}
else
{
n>parent->data?parent->right=t:parent->left=t;
}
}
}
void tree::in(node*q)
{
if(q!=NULL){
in(q->left);

cout<<q->data<<"\t";in(q->right);
}
}
void tree::pre(node*q)
{
if(q!=NULL){
cout<<q->data<<"\t";pre(q->left);
pre(q->right);
}
}
void tree::post(node*q)
{
if(q!=NULL){
post(q->left);
post(q->right);
cout<<q->data<<"\t";
}
}
void tree::traverse()
{
int ch;
cout<<"\n\t1.pre 2.in 3.post 4.exit:";
do{
cout<<"\n\tEnter the option:";
cin>>ch;
switch(ch){
case 1:
cout<<"\n\tpreorder:";
pre(start);
break;
case 2:
cout<<"\n\tInorder:";
in(start);
break;
case 3:
cout<<"\n\tpostorder:";
post(start);
break;
case 4:
break;
}
}while(ch!=4);
}
void main()
{
tree t;
int num,n;
clrscr();
cout<<"\n\tOUTPUT:";
cout<<"\n\t******";
cout<<"\n\tN value:";
cin>>n;
cout<<"\n\tThe values:"<<endl;
for(int i=0;i<n;i++)
{
cin>>num;
t.insert(num);
}
t.traverse();
getch();
}
 

Output:
N value:5

The values:
13
67
45
68
56

1.pre 2.in 3.post 4.exit
 Enter the option:1
preorder:13 67 45 56 68
 Enter the option:2
Inorder:13 45 56 67 68
 Enter the option:3
postorder:56 45 68 67 13
 Enter the option:4


1 comment: