-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBST-Insert&Search.cpp
More file actions
55 lines (52 loc) · 1.09 KB
/
BST-Insert&Search.cpp
File metadata and controls
55 lines (52 loc) · 1.09 KB
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
#include <iostream>
using namespace std;
struct Node {
int data;
Node*left;
Node*right;
};
Node* root = NULL;
struct Node* insert(struct Node* root, int x) {
struct Node* temp = (struct Node*)malloc(sizeof(struct Node*));
temp->data = x;
temp->left = NULL;
temp->right = NULL;
if(root == NULL) {
root = temp;
}
else if(x <= root->data) {
root->left = insert(root->left, x);
} else {
root->right = insert(root->right, x);
}
return root;
}
bool search(Node* root, int data) {
if(root == NULL) {
return false;
}
else if(root->data == data) {
return true;
}
else if(data <= root->data) {
return(search(root->left, data));
}
else {
return(search(root->right, data));
}
}
int main() {
root = insert(root, 10);
root = insert(root,12);
root = insert(root,2);
root = insert(root,22);
root = insert(root,8);
root = insert(root,9);
int n;
cin>>n;
if(search(root,n)) {
cout<<"yes"<<endl;
} else {
cout<<"No"<<endl;
}
}