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]:

  • mini is the largest value in the tree that is smaller than or equal to queries[i]. If such a value does not exist, use -1 instead.
  • maxi is the smallest value in the tree that is greater than or equal to queries[i]. If such a value does not exist, use -1 instead.

Return the array answer.

Example 1
        6
       / \
      2   13
     / \  / \
    1   4 9  15
              /
             14
Inputroot = [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
     \
      9
Inputroot = [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^6
  • n == queries.length
  • 1 <= n <= 10^5
  • 1 <= queries[i] <= 10^6

Asked at 1 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate