206. Floor and Ceil in a BST

Given a root of binary search tree and a key(node) value, find the floor and ceil value for that particular key value.

  • Floor Value Node: Node with the greatest data lesser than or equal to the key value. 
  • Ceil Value Node: Node with the smallest data larger than or equal to the key value.

If a particular floor or ceil value is not present then output -1.

Example 1:

Input : root = [8, 4, 12, 2, 6, 10, 14] , key = 11

Output : [10, 12]

Explanation :

Example 2:

Input : root = [8, 4, 12, 2, 6, 10, 14] , key = 15

Output : [14, -1]

Explanation :

Now Your Turn!

Pick the correct output for the given input

Input : root = [8, 4, 12, 2, 6, 10, 14] , key = 1

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= Number of Nodes <= 5000
  • 1 <= Node.val <= 107
  • 1 <= key <= 107

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* Definition for a binary tree node.
* class TreeNode {
* int data;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int val) : data(val) , left(nullptr) , right(nullptr) {}
* };
**/
 
class Solution{
public:
vector<int> floorCeilOfBST(TreeNode* root,int key){
//your code goes here
}
};
Test Case

Input:

Key
Root