BINARY TREE TRAVERSAL
#include”iostream.h”
#include”conio.h”
#include”stdlib.h”
struct node
{
int data;
struct node *left;
struct node *right;
}*root;
class btraverse
{
public:
btraverse()
{
root=NULL;
}
void create(int);
void preorder(struct node *);
void inorder(struct node *);
void postorder(struct node *);
};
void btraverse::create(int data)
{
struct node *newnode=new node;
newnode->data=data;
newnode->left=NULL;
newnode->right=NULL;
struct node *prev,*temp;
prev=temp=root;
while(temp!=NULL)
{
if(data==temp->data)
{
cout<<"\nData already exists"; return; } else { if(data
{
prev=temp;
temp=temp->left;
}
else
{
prev=temp;
temp=temp->right;
}
}
}
if(root==NULL)
root=newnode;
else if(data
prev->left=newnode;
else
prev->right=newnode;
}
void btraverse::preorder(struct node *t)
{
if(t!=NULL)
{
cout<<" "<
preorder(t->left);
preorder(t->right);
}
}
void btraverse::inorder(struct node *t)
{
if(t!=NULL)
{
inorder(t->left);
cout<<" "<
inorder(t->right);
}
}
void btraverse::postorder(struct node *t)
{
if(t!=NULL)
{
postorder(t->left);
postorder(t->right);
cout<<" "<
}
}
void main()
{
btraverse bt;
int ch,item,n,i;
clrscr();
while(ch<=5) { cout<<"\n"; cout<<"\n1.Create"; cout<<"\n2.Preorder"; cout<<"\n3.Inorder"; cout<<"\n4.Postorder"; cout<<"\n5.Exit"; cout<<"\nEnter ur choice:\t"; cin>>ch;
cout<<"\n"; switch(ch) { case 1: cout<<"\nEnter the total items\n"; cin>>n;
cout<<"Enter the data\n\n"; for(i=0;i
bt.create(item);
}
break;
case 2:
bt.preorder(root);
break;
case 3:
bt.inorder(root);
break;
case 4:
bt.postorder(root);
break;
case 5:
exit(0);
}
}
getch();
}
OUTPUT:
BINARY TREE TRAVERSAL
1.Create
2.Preorder
3.Inorder
4.Postorder
5.Exit
Enter ur choice: 1
Enter the total items
8
Enter the data
30
12
40
10
20
35
50
60
1.Create
2.Preorder
3.Inorder
4.Postorder
5.Exit
Enter ur choice: 2
30 12 10 20 40 35 50 60
1.Create
2.Preorder
3.Inorder
4.Postorder
5.Exit
Enter ur choice: 3
10 12 20 30 35 40 50 60
1.Create
2.Preorder
3.Inorder
4.Postorder
5.Exit
Enter ur choice: 4
10 20 12 35 60 50 40 30
1.Create
2.Preorder
3.Inorder
4.Postorder
5.Exit
Enter ur choice: 5
No comments:
Post a Comment