struct Node {
int val;
Node* left;
Node* right;
Node(int x) : val(x), left(nullptr), right(nullptr) {}
};
int floorBST(Node* root, int key) {
int floor = -1;
while (root) {
if (root->val == key) return root->val;
if (root->val > key) root = root->left;
else {
floor = root->val;
root = root->right;
}
}
return floor;
}
int ceilBST(Node* root, int key) {
int ceil = -1;
while (root) {
if (root->val == key) return root->val;
if (root->val < key) root = root->right;
else {
ceil = root->val;
root = root->left;
}
}
return ceil;
}
int main() {
Node* root = new Node(8);
root->left = new Node(4);
root->right = new Node(12);
root->left->left = new Node(2);
root->left->right = new Node(6);
root->right->left = new Node(10);
root->right->right = new Node(14);
int key = 5;
int f = floorBST(root, key);
int c = ceilBST(root, key);
std::cout << "Floor: " << f << ", Ceil: " << c << std::endl;
return 0;
}The floor of 5 in the BST is 4 because 4 is the greatest value less than 5. The ceil of 5 is 6 because 6 is the smallest value greater than 5.
Floor is the greatest value less than or equal to the key, and ceil is the smallest value greater than or equal to the key in the BST.
The condition to update floor is incorrect. It updates floor when root->val < key, but for key=1, it incorrectly moves right and sets floor to 2, which is greater than 1. The correct floor should be -1.
Floor is 10 because it is the greatest value less than 13. Ceil is 15 because it is the smallest value greater than 13.
Floor of 17 is 15, ceil is 20. Nodes with values 15 and 20 are counted. Since 17 is not in BST, nodes between 15 and 20 inclusive are 15 and 20 only. So count is 2 nodes.