Binary Search Trees BST basics
384. Floor and Ceil in a BST
You are given root, the root node of a binary search tree, and an array keys. For each key, find its floor
and its ceiling among the values in the tree.
The floor of a key is the largest value in the tree that is less than or equal to the key. The ceiling
is the smallest value in the tree that is greater than or equal to the key. If no value qualifies, the answer
for that side is -1. Every value is 0 or more, so -1 never looks like a real value.
Return an array answer with one entry per key, in the order the keys are given:
answer[j] = [floor, ceiling] for keys[j].
In a binary search tree, every value in a node's left subtree is smaller than the node's value, and every value in its right subtree is larger. The values in the tree are distinct.
The examples write a tree level by level, from left to right, with null where a child is missing. So
root = [5,8,null,3] is the root 5 with a left child 8 and no right child, and 8 has a left child 3. The
missing children after the last node are left out.
Example 1
Input: root = [50, 20, 80, 10, 35, 65, 95, null, null, 30, 40]
keys = [33, 65, 5, 99]
[[30,35],[65,65],[-1,10],[95,-1]]Explanation: From smallest to largest, the values are 10, 20, 30, 35, 40, 50, 65, 80, 95. 33 lies between 30 and 35. 65 is in the tree, so it is its own floor and its own ceiling. Nothing is at most 5, and nothing is at least 99, so those sides are −1.
Example 2
Input: root = [7], keys = [7, 0, 1000000000]
[[7,7],[-1,7],[7,-1]]Explanation: With one node, 7 answers every side that exists. 0 has nothing below it, and 109 has nothing above it.
Example 3
Input: root = [0, null, 1000000000]
keys = [0, 500000000, 1000000000]
[[0,0],[0,1000000000],[1000000000,1000000000]]Explanation: 0 is a real value here, so the floor of 500000000 is 0, not −1. The smallest and largest allowed values both appear.
Check your understanding
Work out the answer for this input before you write any code.
Constraints
1 ≤ number of nodes ≤ 1050 ≤ Node.val ≤ 109- The tree has at most 1000 levels.
- The tree is a binary search tree, and its values are distinct.
1 ≤ keys.length ≤ 1040 ≤ keys[j] ≤ 109
Clarifying questions
What you would ask an interviewer before writing any code.