/*binary tree with pre,in,post order traversing
compiler- Turbo c++ author- Mangilal Sharma
--------------------------------------------------------*/
#include<iostream.h>
#include<conio.h>
#include<stdlib.h>
struct b_node
{
int data;
struct b_node *left;
struct b_node *right;
}*root;
class binary
{
public:
int count;
struct b_node *insert(struct b_node *root,int num);
void preorder(struct b_node *root);
void inorder(struct b_node *root);
void postorder(struct b_node *root);
binary();
};
struct b_node *binary::insert(struct b_node *root,int num)
{
if(root==NULL)
{
root=(struct b_node *)malloc(sizeof(struct b_node));
root->data=num;
root->left=NULL;
root->right=NULL;
count++;
}
else
{
if(count%2==0)
{
root->left=insert(root->left,num);
}
else
{
root->right=insert(root->right,num);
}
}
return(root);
}
void binary::preorder(struct b_node *root)
{
if(root!=NULL)
{
cout<<root->data;
preorder(root->left);
preorder(root->right);
}
}
void binary::inorder(struct b_node *root)
{
if(root!=NULL)
{
inorder(root->left);
cout<<root->data;
inorder(root->right);
}
}
void binary::postorder(struct b_node *root)
{
if(root!=NULL)
{
postorder(root->left);
postorder(root->right);
cout<<root->data;
}
}
binary::binary()
{
struct b_node *root=NULL;
count=-1;
int choice,num;
do
{
cout<<"\n\t\t\tBinary Tree\n";
cout<<"\t\t1. Insert node in tree\n";
cout<<"\t\t2. Preorder Traversal\n";
cout<<"\t\t3. Inorder traversal\n";
cout<<"\t\t4. Postoder Traversl\n";
cout<<"\t\t5. Main menu\n";
cout<<"\t\t6. Exit\n";
cout<<"\t\tEnter ur choice=";
cin>>choice;
switch(choice)
{
case 1:
cout<<"enter No. to add in tree & -999 to exit\n";
cin>>num;
while(num!=-999)
{
root=insert(root,num);
cin>>num;
}break;
case 2:
cout<<"Preorder Traversing\n";
preorder(root);break;
case 3:
cout<<"Inorder Traversing\n";
inorder(root);break;
case 4:
cout<<"Postorder Traversing";
postorder(root);break;
case 5: return;
case 6: exit(1);
default:cout<<"Wrong Choice";
}
}while(1);
}
/*=========================13Nov.,2010=============================*/
Thanks for nice post.C programming details here
ReplyDelete