You are on page 1of 4

C++ Implementation of Binary Trees

The following program implements the concept of binary Trees in C++. The data is entered into the tree in the
following order.
If you are entering the nos. in the order 1,2,3,4,5,6,7.. they will be taken in the tree as in the figure.
The program also implements pre-order ,in-order and post order traversal in the Binary Tree
Run the program. The real strength of the Program lies in the use or recursive functions. It’s a bit complicated.

#include<iostream.h>
#include<conio.h> 1
#include<stdio.h>
#include<stdlib.h>
struct node
{ 2
int data;
3
node *left;
node *right;
};
4 5 6 7
node *tree=NULL;
node *insert(node *tree,int ele);

void preorder(node *tree);


void inorder(node *tree);
void postorder(node *tree);
int count=1;
int i,index[1000];

void main()
{
clrscr();
int ch,ele,x;
do
{
clrscr();
cout<<"\n\t\a\a1----INSERT A NODE IN A BINARY TREE.\a\a";
cout<<"\n\t\a\a2----PRE-ORDER TRAVERSAL.\a\a";
cout<<"\n\t\a\a3----IN-ORDER TRAVERSAL.\a\a";
cout<<"\n\t\a\a4----POST-ORDER TRAVERSAL.\a\a";
cout<<"\n\t\a\a5----EXIT.\a\a";
cout<<"\n\t\a\aENTER CHOICE::\a\a";
cin>>ch;
switch(ch)
{
case 1:
cout<<"\n\t\a\aENTER THE ELEMENT::\a\a";
cin>>ele;
x=count;
for(i=0;x/2!=0;i++)
{
index[i]=x%2;
x=x/2;
}
tree=insert(tree,ele);
break;

case 2:
cout<<"\n\t\a\a****PRE-ORDER TRAVERSAL OF A TREE****\a\a\n\t";
preorder(tree);
break;

case 3:
cout<<"\n\t\a\a****IN-ORDER TRAVERSAL OF A TREE****\a\a\n\t";
inorder(tree);
break;

case 4:
cout<<"\n\t\a\a****POST-ORDER TRAVERSAL OF A TREE****\a\a\n\t";
postorder(tree);
break;

case 5:
exit(0);
}
cout<<"\n\t\a\a****ENTER ANY KEY****";
getch();
}while(ch!=5);
}

node *insert(node *tree,int ele)


{ i--;
if(tree==NULL)
{
tree=new node;
tree->left=tree->right=NULL;
tree->data=ele;
count++;
}
else
{
if(index[i]==0)
tree->left=insert(tree->left,ele);
else
tree->right=insert(tree->right,ele);
}
return(tree);
}

void preorder(node *tree)


{
if(tree!=NULL)
{
cout<<tree->data<<" ";
preorder(tree->left);
preorder(tree->right);
}
}

void inorder(node *tree)


{
if(tree!=NULL)
{
inorder(tree->left);
cout<<tree->data<<" ";
inorder(tree->right);
}
}

void postorder(node *tree)


{
if(tree!=NULL)
{
postorder(tree->left);
postorder(tree->right);
cout<<tree->data<<" ";
}
}

You might also like