Complete the code to find the floor value in a BST.
int floorBST(struct Node* root, int key) {
int floor = -1;
while (root != NULL) {
if (root->data == key) {
floor = root->data;
break;
} else if (root->data > key) {
root = root->left;
} else {
floor = root->data;
root = root->[1];
}
}
return floor;
}The floor is the greatest value less than or equal to the key. When root->data is less than key, we move to the right subtree to find a closer value.
Complete the code to find the ceil value in a BST.
int ceilBST(struct Node* root, int key) {
int ceil = -1;
while (root != NULL) {
if (root->data == key) {
ceil = root->data;
break;
} else if (root->data < key) {
root = root->right;
} else {
ceil = root->data;
root = root->[1];
}
}
return ceil;
}The ceil is the smallest value greater than or equal to the key. When root->data is greater than key, we move to the left subtree to find a closer value.
Fix the error in the code to correctly find the floor in BST.
int floorBST(struct Node* root, int key) {
int floor = -1;
while (root != NULL) {
if (root->data == key) {
floor = root->data;
break;
} else if (root->data < key) {
floor = root->data;
root = root->[1];
} else {
root = root->left;
}
}
return floor;
}When root->data is less than key, we should move to the right child to find a closer floor value. The original code incorrectly moves to the left child.
Fill both blanks to complete the function that finds ceil in BST.
int ceilBST(struct Node* root, int key) {
int ceil = -1;
while (root != NULL) {
if (root->data == key) {
ceil = root->data;
break;
} else if (root->data > key) {
ceil = root->data;
root = root->[1];
} else {
root = root->[2];
}
}
return ceil;
}When root->data > key, move left to find smaller ceil candidates. When root->data < key, move right to find larger values.
Fill all three blanks to complete the function that finds floor and ceil in BST and returns them in an array.
int* floorAndCeilBST(struct Node* root, int key) {
static int result[2];
result[0] = -1; // floor
result[1] = -1; // ceil
struct Node* current = root;
while (current != NULL) {
if (current->data == key) {
result[0] = current->data;
result[1] = current->data;
break;
} else if (current->data < key) {
result[0] = current->data;
current = current->[1];
} else {
result[1] = current->data;
current = current->[2];
}
}
return result;
}
// Usage example:
// int* res = floorAndCeilBST(root, 15);
// printf("Floor: %d, Ceil: %d\n", res[[3]], res[1]);For floor, move right when current->data < key. For ceil, move left when current->data > key. The floor is stored at index 0 in the result array.
