Friday, October 28, 2011

Binary Search TREE

#include<iostream>

#include<stdlib.h>


using namespace std;



struct node

{

int d;

struct node *left;

struct node *right;

};



struct node *root;


void init();

void empty();

int insert(int);

void search(int);


 



void init()

{

root=(struct node *)malloc(sizeof(struct node));

root=NULL;

}



int insert(int x)

{

struct node *p,*previous,*current;


p=(struct node *)malloc(sizeof(struct node));



 if (p==NULL)

 { 

 cout<<"\nOut of Memory";

 return 0;

 }


p->d=x;

p->left=NULL;

p->right=NULL;


 if(root==NULL)

 {

root=p;

 return 1;

 }
 


previous=NULL;

current=root;



 while (current!=NULL)

 {

 previous=current;

 
if (p->d<current->d)
 
  current=current->left;

  else
 
  current=current->right;

 }



if(p->d<previous->d)
 
previous->left=p;

else
 
previous->right=p;


return 1;


}








void search(int sno)

{

struct node*t;

t=(struct node *)malloc(sizeof(struct node));

t=root;



 while(t!=NULL && t->d !=sno)

 {

if(t->d>sno)
{ t=t->left; }

else
 { t=t->right; }

}



if(t)

cout<<"\nThe Search Element is Present";

else

cout<<"\nElement is not Present";

}




int main()

{

int c,no,x;

init();



do

{

cout<<"\n1.Insert";
cout<<"\n2.Search";
cout<<"\n3.Exit";

cout<<"\nEnter Your Choice:\t";

cin>>c;



switch(c)

{

case 1: cout<<"\nEnter the Element to Insert:\t";
        
        cin>>no;

        x=insert(no);

        if(x==1)

         cout<<"\nsucessful Insertion";

        else

         cout<<"\nError in insertion";

        break;

case 2: cout<<"\nEnter the Element to Search: \t";
        cin>>no;

        search(no);

        break;

case 3: exit (0); break;

default: cout<<"\nEnter Any No. Between 1/3";

}


}while(c<3);


return 0;

}