-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathbinarysearchtree.cpp
96 lines (95 loc) · 1.61 KB
/
binarysearchtree.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include<iostream>
using namespace std;
struct node{
int data;
node* left;
node* right;
};
node* root=NULL;
node* getnewnode(){
node* currentnode=new node;
currentnode->left=NULL;
currentnode->right=NULL;
return currentnode;
}
void insert(int data){
if(root==NULL){
root=getnewnode();
root->data=data;
}
else{
node* currentnode=root;
node* prev=NULL;
int x=0;
while(currentnode!=NULL){
if(currentnode->data>=data){
prev=currentnode;
currentnode=currentnode->left;
x=0;
}
else{
prev=currentnode;
currentnode=currentnode->right;
x=1;
}
}
if(x==1){
currentnode=getnewnode();
currentnode->data=data;
prev->right=currentnode;
}
else if(x==0){
currentnode=getnewnode();
currentnode->data=data;
prev->left=currentnode;
}
}
}
bool search(int data){
node* currentnode=root;
bool check;
if(currentnode==NULL)
return false;
else{
while(1){
if(currentnode==NULL){
check=false;
break;
}
else if(currentnode->data==data){
check=true;
break;
}
else if(currentnode->data>=data)
currentnode=currentnode->left;
else
currentnode=currentnode->right;
}
}
return check;
}
int main(){
int test;
cout<<"Enter Test Case: "<<endl;
cin>>test;
while(test--){
cout<<"Enter Number: "<<endl;
int x;
cin>>x;
insert(x);
}
cout<<"Enter The Number of Queries: "<<endl;
int t;
cin>>t;
while(t--){
int x;
cout<<"Enter The Number to Search: "<<endl;
cin>>x;
bool check=search(x);
if(check==true)
cout<<"The Number is Found in Tree: "<<endl;
else
cout<<"The Number is Not Found in Tree: "<<endl;
}
return 0;
}