#include <iostream>
using namespace std;
struct Node {
int val;
Node* left;
Node* right;
Node(int x) : val(x), left(nullptr), right(nullptr) {}
};
Node* insert(Node* root, int val) {
if (!root) return new Node(val);
if (val < root->val) root->left = insert(root->left, val);
else root->right = insert(root->right, val);
return root;
}
int findFloor(Node* root, int target) {
int floor = -1;
while (root) {
if (root->val == target) {
floor = root->val;
break;
} else if (root->val > target) {
root = root->left; // move left to find smaller or equal
} else {
floor = root->val; // update floor candidate
root = root->right; // move right to find closer floor
}
}
return floor;
}
int findCeil(Node* root, int target) {
int ceil = -1;
while (root) {
if (root->val == target) {
ceil = root->val;
break;
} else if (root->val < target) {
root = root->right; // move right to find larger or equal
} else {
ceil = root->val; // update ceil candidate
root = root->left; // move left to find closer ceil
}
}
return ceil;
}
int main() {
Node* root = nullptr;
int values[] = {8,4,12,2,6,10,14};
for (int v : values) root = insert(root, v);
int target = 5;
int floor = findFloor(root, target);
int ceil = findCeil(root, target);
cout << "Floor: " << floor << "\n";
cout << "Ceil: " << ceil << "\n";
return 0;
}
loop to traverse BST nodes until null
if (root->val == target) { floor = root->val; break; }
exact match found, floor or ceil is target itself
else if (root->val > target) { root = root->left; }
move left to find smaller or equal values for floor
else { floor = root->val; root = root->right; }
update floor candidate and move right to find closer floor
else if (root->val < target) { root = root->right; }
move right to find larger or equal values for ceil
else { ceil = root->val; root = root->left; }
update ceil candidate and move left to find closer ceil