Sunday, July 4, 2010

BINARY TREE CREATION AND TRAVERSAL(DS)

Buzz It
#include<iostream.h>
#include<conio.h>
struct node
{
int data;
node *left;
node *right;
};
class tree
{
public:
int a,b;
node *head,*root;
node *createnode(int a);
void createtree (node *root);
void inorder(node *root);
void preorder(node *root);
void postorder(node *root);
};
node* tree::createnode(int a)
{
head=new node;
head->data=a;
head->left=NULL;
head->right=NULL;
return(head);
}
void tree::createtree(node *root)
{
cout<<"do you want to create left child for"<<root->data<<"\n";
cin>>b;
if(b==1)
{
cout<<"enter data\n";
cin>>a;
root->left=createnode(a);
createtree(root->left);
}
cout<<"do you want to create right child for"<<root->data<<"\n";
cin>>b;
if(b==1)
{
cout<<"enter data\n";
cin>>a;
root->right=createnode(a);
createtree(root->right);
} }
void tree::inorder(node *root)
{
if(root!=NULL)
{
inorder(root->left);
cout<<root->data;
inorder(root->right);
}}
void tree::preorder(node *root)
{
if(root!=NULL)
{
cout<<root->data;
preorder(root->left);
preorder(root->right);
}}
void tree::postorder(node *root)
{
if(root!=NULL)
{
postorder(root->left);
postorder(root->right);
cout<<root->data;
}}
void main()
{
clrscr();
int a,c;
tree ob;
cout<<"enter root data\n";
cin>>a;
ob.root=ob.createnode(a);
do
{
cout<<"menu\n1-createtree\n2-inorder\n3-preorder\n4-postorder\n";
cin>>c;
switch(c)
{
case 1:ob.createtree(ob.root);
break;
case 2:ob.inorder(ob.root);
break;
case 3:ob.preorder(ob.root);
break;
case 4:ob.postorder (ob.root);
break;
}}
while(c<=4);
getch();
}

OUTPUT:
enter root data
5
menu
1-createtree
2-inorder
3-preorder
4-postorder
1
do you want to create left child for5
1e
Enter data
4
do you want to create left child for4
1e
Enter data
3
do you want to create left child for3
0
do you want to create right child for3
0
do you want to create right child for4
1e
Enter data
6
do you want to create left child for6
0
do you want to create right child for6
0
do you want to create right child for5
1e
Enter data
7
do you want to create left child for7
0
do you want to create right child for7
0
menu
1-createtree
2-inorder
3-preorder
4-postorder
23
4657
menu
1-createtree
2-inorder
3-preorder
4-postorder
3
54367
menu
1-createtree
2-inorder
3-preorder
4-postorder
43
6475

0 comments:

Post a Comment