The Closest Nodes Queries in a Binary Search Tree interview question asks you to process multiple target values against a BST. For each target, you must find two values from the tree: the largest value less than or equal to the target (floor) and the smallest value greater than or equal to the target (ceiling). If no such value exists, you return -1 for that part of the query.
Google uses the Closest Nodes Queries in a Binary Search Tree coding problem to see if you can identify when a data structure's inherent property (like a BST's structure) might actually be a bottleneck. While a BST can be searched in O(H) time, if the tree is unbalanced, H becomes N. Preprocessing the tree into a sorted array and using binary search is often a more robust solution in an interview setting.
The most efficient Binary Search Tree interview pattern for this problem is:
bisect_left (or lower_bound) on the sorted array to find the ceiling. The element immediately before it will be the floor. This takes O(log N) per query.BST:
8
/
2 12
Target query: 10
[2, 8, 12].10 in [2, 8, 12].10 would fit between 8 and 12.8.12.
Result: [8, 12].
If the query was 15, the floor is 12 and the ceiling is -1.Q queries results in O(N * Q) time, which will time out.Always check if the problem guarantees a balanced BST. If it doesn't, a simple tree traversal might be O(N). In such cases, converting the tree to a sorted array is a safer and often faster strategy for multiple queries.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Closest Binary Search Tree Value | Easy | Solve | |
| Convert BST to Greater Tree | Medium | Solve | |
| Binary Search Tree to Greater Sum Tree | Medium | Solve | |
| Inorder Successor in BST | Medium | Solve | |
| Recover Binary Search Tree | Medium | Solve |