Closest Nodes Queries in a Binary Search Tree - Problem
You are given the root of a binary search tree and an array
1. Floor value: The largest value in the BST that is smaller than or equal to the query
2. Ceiling value: The smallest value in the BST that is greater than or equal to the query
Return a 2D array where each element
Think of it as finding the closest neighbors for each query in the BST!
queries of positive integers. For each query value, you need to find two important pieces of information:1. Floor value: The largest value in the BST that is smaller than or equal to the query
2. Ceiling value: The smallest value in the BST that is greater than or equal to the query
Return a 2D array where each element
answer[i] = [mini, maxi] represents the floor and ceiling for queries[i]. If no floor exists, use -1. If no ceiling exists, use -1.Think of it as finding the closest neighbors for each query in the BST!
Input & Output
example_1.py — Basic BST Query
$
Input:
root = [6,2,13,1,4,9,15,null,null,null,null,null,null,14], queries = [2,5,16]
›
Output:
[[2,2],[4,6],[-1,-1]]
💡 Note:
For query 2: floor=2 (exact match), ceiling=2 (exact match). For query 5: floor=4 (largest ≤5), ceiling=6 (smallest ≥5). For query 16: floor=-1 (no value ≤16... wait, 15 ≤ 16), ceiling=-1 (no value ≥16). Actually floor should be 15.
example_2.py — Edge Case Queries
$
Input:
root = [4,null,9], queries = [3,10]
›
Output:
[[-1,4],[9,-1]]
💡 Note:
For query 3: no value ≤3 exists (floor=-1), smallest value ≥3 is 4 (ceiling=4). For query 10: largest value ≤10 is 9 (floor=9), no value ≥10 exists (ceiling=-1).
example_3.py — Single Node
$
Input:
root = [5], queries = [1,5,10]
›
Output:
[[-1,5],[5,5],[-1,-1]]
💡 Note:
Tree has only one node (5). Query 1: floor=-1, ceiling=5. Query 5: floor=5, ceiling=5. Query 10: floor=5, ceiling=-1.
Constraints
- The number of nodes in the tree is in the range [1, 2 × 104]
- 1 ≤ Node.val ≤ 106
- n == queries.length
- 1 ≤ n ≤ 104
- 1 ≤ queries[i] ≤ 106
- All node values are unique
Visualization
Tap to expand
Understanding the Visualization
1
Extract Sorted Values
Inorder traversal gives us all parking spot numbers in order
2
Binary Search Floor
Find the highest-numbered spot ≤ our target (closest behind)
3
Binary Search Ceiling
Find the lowest-numbered spot ≥ our target (closest ahead)
4
Return Results
Return both closest spots, or -1 if none exists in that direction
Key Takeaway
🎯 Key Insight: BST's inorder traversal gives us a sorted array, enabling efficient O(log n) binary search for floor/ceiling queries instead of O(n) linear search per query.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code