Complete the code to find the floor value in a BST.
int floorInBST(Node* root, int key) {
int floor = -1;
while (root != nullptr) {
if (root->data == key) {
floor = root->data;
break;
} else if (root->data > key) {
root = root->[1];
} else {
floor = root->data;
root = root->right;
}
}
return floor;
}When the current node's data is greater than the key, we move to the left child to find a smaller or equal value.
Complete the code to find the ceil value in a BST.
int ceilInBST(Node* root, int key) {
int ceil = -1;
while (root != nullptr) {
if (root->data == key) {
ceil = root->data;
break;
} else if (root->data < key) {
root = root->[1];
} else {
ceil = root->data;
root = root->left;
}
}
return ceil;
}When the current node's data is less than the key, we move to the right child to find a larger or equal value.
Fix the error in the code to correctly find the floor in BST.
int floorInBST(Node* root, int key) {
int floor = -1;
while (root != nullptr) {
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 current node's data is less than key, we move to the right child to find a closer or equal value.
Fill both blanks to complete the code that finds ceil in BST.
int ceilInBST(Node* root, int key) {
int ceil = -1;
while (root != nullptr) {
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 current node's data is greater than key, move left to find smaller or equal values. Otherwise, move right to find larger values.
Fill all three blanks to complete the code that finds floor and ceil in BST.
pair<int, int> floorAndCeil(Node* root, int key) {
int floor = -1, ceil = -1;
while (root != nullptr) {
if (root->data == key) {
floor = root->data;
ceil = root->data;
break;
} else if (root->data < key) {
floor = root->data;
root = root->[1];
} else {
ceil = root->data;
root = root->[2];
}
}
return {floor, ceil};
}
int main() {
Node* root = nullptr;
// Assume BST is built here
int key = 15;
auto result = floorAndCeil(root, key);
cout << "Floor: " << result.[3] << ", Ceil: " << result.second << endl;
return 0;
}When current node's data is less than key, move right to find closer floor. When greater, move left to find closer ceil. The floor value is stored in the first element of the pair.