C++ Program to implement Traversal in Binary tree.

In computer sciencetree traversal (also known as tree search) refers to the process of visiting (examining and/or updating) each node in a tree data structure, exactly once, in a systematic way. Such traversals are classified by the order in which the nodes are visited. The following algorithms are described for a binary tree, but they may be generalized to other trees as well.

1.Pre-order

2.

In-order (symmetric)

3.Post-order



 #include<iostream.h>
#include<conio.h>
struct node
{
int info;
node *left;
node *right;
}*root;
void insert(int,node*);
void insert(int item)
{
if(root!=NULL)
insert(item, root);
else
{
root=new node;
root->info=item;
root->left=NULL;
root->right=NULL;
}
}
void insert(int item, node *leaf)
{
if(item< leaf->info)
{
if(leaf->left!=NULL)
insert(item,leaf->left);
else
{
leaf->left=new node;
leaf->left->info=item;
leaf->left->left=NULL;
leaf->left->right=NULL;
}
}
else if(item>=leaf->info)
{
if(leaf->right!=NULL)
insert(item, leaf->right);
else
{
leaf->right=new node;
leaf->right->info=item;
leaf->right->left=NULL;
leaf->right->right=NULL;
}
}
}
void preorder(node *leaf)
{
if(leaf!=NULL)
{
cout<<" "<<leaf->info;
preorder(leaf->left);
preorder(leaf->right);
}
}
void inorder(node*leaf)
{
if(leaf!=NULL)
{
inorder(leaf->left);
cout<<" "<<leaf->info;
inorder(leaf->right);
}
}
void postorder(node *leaf)
{
if(leaf!=NULL)
{
postorder(leaf->left);
postorder(leaf->right);
cout<<" "<<leaf->info;
}
}
void main()
{
clrscr();
int op;
int item;
while(op!=5)
{
cout<<"\nSelect Option\n1.Insert item\n2.preorder\n3.inorder\n4.postorder\n5.exit\n";
cin>>op;
switch(op)
{
case 1:
cout<<"Enter the item to insert in tree :";
cin>>item;
insert(item);
break;
case 2:
cout<<"Preorder :";
preorder(root);
break;
case 3:
cout<<"Inorder :";
inorder(root);
break;
case 4:
cout<<"Postorder :";
postorder(root);
break;
case 5:
cout<<"Press any to exit";
break;
default:
cout<<"Invalid option";
}
getch();
}

}

0 comments:

Post a Comment