#include <iostream>
using namespace std;
struct tree
{
int data;
struct tree *right,*left;
};
typedef struct tree node;
node *head =NULL;
node *search_bst(node *&temp,int srch)
{
if(temp==NULL)
{
return temp;
}
if(temp->data==srch)
{
return temp;
}
else if(temp->data < srch ) ///compare temp->data with value
{
search_bst(temp->right,srch); ///if the value is grater then temp->data
}
else
{
search_bst(temp->left,srch); ///if the value is smaller then temp->data
}
}
node *insert_bst(node *&temp,int value) ///save the address in temp
{
if(temp==NULL)
{
temp = new node();
temp->data=value;
temp->right=NULL;
temp->left=NULL;
}
else if(temp->data <= value ) ///compare temp->data with value
{
insert_bst(temp->right,value); ///if the value is grater then temp->data
}
else
{
insert_bst(temp->left,value); ///if the value is smaller then temp->data
}
}
void inorder(node *temp)
{
if(temp==NULL)
{
return;
}
inorder(temp->left);
cout<<temp->data<<" ";
inorder(temp->right);
}
int main()
{
int flag=1,n,value,srch;
while(flag==1)
{
cout<<"Press 1 for Insert Data 0 to Exit: ";
cin>>n;
if(n!=1) break;
cout<<"Value: ";
cin>>value;
insert_bst(head,value);
}
cout<<"
Print In order: ";
inorder(head);
cout<<endl;
cout<<"What You Want to Search: ";
cin>>srch;
node *check = search_bst(head,srch);
if(check != NULL)
{
cout<<"
Found"<<endl;
}
else
{
cout<<"
Not Found"<<endl;
}
return 0;
}
Output
Press 1 for Insert Data 0 to Exit: 1
Value: 3
Press 1 for Insert Data 0 to Exit: 1
Value: 8
Press 1 for Insert Data 0 to Exit: 1
Value: 2
Press 1 for Insert Data 0 to Exit: 1
Value: 9
Press 1 for Insert Data 0 to Exit: 1
Value: 0
Press 1 for Insert Data 0 to Exit: 1
Value: 1
Press 1 for Insert Data 0 to Exit: 0
Print In order: 0 1 2 3 8 9
What You Want to Search: 8
Found
Add your comment