Magicsheet logo

Closest Nodes Queries in a Binary Search Tree

Medium
25%
Updated 8/1/2025

Closest Nodes Queries in a Binary Search Tree

What is this problem about?

The Closest Nodes Queries in a Binary Search Tree interview question asks you to process multiple target values against a BST. For each target, you must find two values from the tree: the largest value less than or equal to the target (floor) and the smallest value greater than or equal to the target (ceiling). If no such value exists, you return -1 for that part of the query.

Why is this asked in interviews?

Google uses the Closest Nodes Queries in a Binary Search Tree coding problem to see if you can identify when a data structure's inherent property (like a BST's structure) might actually be a bottleneck. While a BST can be searched in O(H) time, if the tree is unbalanced, H becomes N. Preprocessing the tree into a sorted array and using binary search is often a more robust solution in an interview setting.

Algorithmic pattern used

The most efficient Binary Search Tree interview pattern for this problem is:

  1. In-order Traversal: Convert the BST into a sorted array. This takes O(N) time and handles the "unbalanced tree" risk.
  2. Binary Search: For each query, perform a bisect_left (or lower_bound) on the sorted array to find the ceiling. The element immediately before it will be the floor. This takes O(log N) per query.

Example explanation

BST: 8 / 2 12 Target query: 10

  1. In-order traversal: [2, 8, 12].
  2. Binary search for 10 in [2, 8, 12].
  3. 10 would fit between 8 and 12.
  4. Floor (largest val <= 10) is 8.
  5. Ceiling (smallest val >= 10) is 12. Result: [8, 12]. If the query was 15, the floor is 12 and the ceiling is -1.

Common mistakes candidates make

  • Searching the Tree Directly: If the tree is a "skewed" tree (basically a linked list), searching it directly for each of the Q queries results in O(N * Q) time, which will time out.
  • Handling -1: Forgetting to handle cases where the target is smaller than the minimum or larger than the maximum value in the tree.
  • Redundant Traversals: Performing a full traversal for every single query instead of doing it once.

Interview preparation tip

Always check if the problem guarantees a balanced BST. If it doesn't, a simple tree traversal might be O(N). In such cases, converting the tree to a sorted array is a safer and often faster strategy for multiple queries.

Similar Questions