PROGRAM TO MAKE A BINARY SEARCH TREE AND TRAVERSE IT IN PREORDER,INORDER,POSTORDER METHOD.

#include<iostream.h>                         //HEADER FILES
#include<ctype.h>
#include<stdio.h>

struct tree                                       //STRUCTURE FOR TREE NODE
{
int data;
tree *left,*right;
};                                                //STRUCTURE FOR LIST
struct list
{
int num;
list * next;
};

list *head=NULL,*temp,*curr;
FILE* file;
void put(int no)                                 //PUT  NO. INTO LIST
{
temp=new list;
temp->num=no;
temp->next=NULL;
if(head==NULL)
{
head=temp;
curr=temp;
}
else
{
curr->next=temp;
curr=temp;
}
}

void getdata()
{
char ch;
int no,flag=1;
file=fopen("input.txt","r");
do
{
if(flag)
{
no=0;
flag=0;
}
ch=getc(file);
if(isdigit(ch))
no=no*10+ch-48;
else if(ch==' ')
{
flag=1;
put(no);
}
}while(ch!='n');
fclose(file);
}

void makenode(tree **garb,int num)        //PREPARE A NODE
{
(*garb)->data=num;
(*garb)->left=NULL;
(*garb)->right=NULL;
}

void maketree(tree *garb,tree **base)        //INSERT NODE INTO TREE
{
if((*base)==NULL)
{
*base=garb;
return;
}
else if(garb->data==(*base)->data)
{
cout<<"  "<<garb->data;
return;
}
else if(garb->data<(*base)->data)
maketree(garb,&((*base)->left));
else
maketree(garb,&((*base)->right));
}

void preorder(tree *node)         //PREORDER TRAVERSAL
{
cout<<" "<<node->data;
if(node->left!=NULL)
preorder(node->left);
if(node->right!=NULL)
preorder(node->right);
}

void inorder(tree *node)          //INORDER TRAVERSAL
{
if(node->left!=NULL)
inorder(node->left);
cout<<" "<<node->data;
if(node->right!=NULL)
inorder(node->right);
}

void postorder(tree *node)         //POST ORDER TRAVERSAL
{
if(node->left!=NULL)
postorder(node->left);
if(node->right!=NULL)
postorder(node->right);
cout<<" "<<node->data;
}
void main()                        //EXECUTION STARTS HERE
{
tree *garb,*root=NULL;
getdata();
temp=head;
cout<<"n DUPLICATE ELEMENTS ARE : n";
while(temp!=NULL)
{
garb=new tree;
makenode(&garb,temp->num);
maketree(garb,&root);
temp=temp->next;
}
cout<<"n PREORDER TRAVERSE :";
preorder(root);
cout<<"n INORDER TRAVERSE :";
inorder(root);
cout<<"n POSTORDER TRAVERSE :";
postorder(root);
free(garb);
free(root);
cout<<"n";
}

Advertisements

2 thoughts on “PROGRAM TO MAKE A BINARY SEARCH TREE AND TRAVERSE IT IN PREORDER,INORDER,POSTORDER METHOD.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s