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