-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFloor_in_Binary_Search_Tree.cpp
80 lines (66 loc) · 1.5 KB
/
Floor_in_Binary_Search_Tree.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
//{ Driver Code Starts
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *right;
Node *left;
Node(int x) {
data = x;
right = NULL;
left = NULL;
}
};
// } Driver Code Ends
// Function to search a node in BST.
class Solution{
public:
int floor(Node* root, int x) {
if (root == NULL) return -1;
int Floor = -1;
while(root != NULL){
if(root->data == x)
{
Floor = root->data;
return Floor;
}
if(root->data > x) root = root->left;
else
{
Floor = root->data;
root = root->right;
}
}
return Floor;
}
};
//{ Driver Code Starts.
Node *insert(Node *tree, int val) {
Node *temp = NULL;
if (tree == NULL) return new Node(val);
if (val < tree->data) {
tree->left = insert(tree->left, val);
} else if (val > tree->data) {
tree->right = insert(tree->right, val);
}
return tree;
}
int main() {
int T;
cin >> T;
while (T--) {
Node *root = NULL;
int N;
cin >> N;
for (int i = 0; i < N; i++) {
int k;
cin >> k;
root = insert(root, k);
}
int s;
cin >> s;
Solution obj;
cout << obj.floor(root, s) << "\n";
}
}
// } Driver Code Ends