Closest Nodes Queries in a Binary Search Tree

Medium

Description

Given a BST root and array of queries, for each query return the [floor, ceiling] pair from the tree, or -1 if not found.

Examples

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],[15,-1]]
Explanation:

Closest values.

Input:root = [6,2,13,1,4,9,15,null,null,null,null,null,null,14], queries = [1]
Output:[1]
Explanation:

Edge case with a single-element array.

Input:root = [10,5,20,3,7,15,25,null,null,6,8], queries = [12,3,30]
Output:[[8,15],[3,3],[25,-1]]
Explanation:

For query 12: closest smaller is 8, closest larger is 15. For query 3: the value 3 exists in BST, so both smaller and larger are 3. For query 30: closest smaller is 25, no larger value exists so -1.

Constraints

  • 2 ≤ nodes ≤ 10⁵

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!