Closest Nodes Queries in a Binary Search Tree
You are given the root of a binary search tree and an array queries of size n consisting of positive integers.
Find a 2D array answer of size n where answer[i] = [mini, maxi]:
miniis the largest value in the tree that is smaller than or equal toqueries[i]. If such a value does not exist, use-1instead.maxiis the smallest value in the tree that is greater than or equal toqueries[i]. If such a value does not exist, use-1instead.
Return the array answer.
Example 1
6
/ \
2 13
/ \ / \
1 4 9 15
/
14Input
root = [6,2,13,1,4,9,15,null,null,null,null,null,null,14], queries = [2,5,16]Output
[[2,2],[4,6],[15,-1]]For the queries 2, 5, and 16, the closest lower and upper values are [2,2], [4,6], and [15,-1], respectively.
Example 2
4
\
9Input
root = [4,null,9], queries = [3]Output
[[-1,4]]The largest number smaller than or equal to 3 does not exist, and the smallest number greater than or equal to 3 is 4.
Constraints
- The number of nodes in the tree is in the range
[2, 10^5]. 1 <= Node.val <= 10^6n == queries.length1 <= n <= 10^51 <= queries[i] <= 10^6