Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
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 a such value does not exist, add -1 instead.maxi is the smallest value in the tree that is greater than or equal to queries[i]. If a such value does not exist, add -1 instead.Return the array answer.
Example 1:
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: We answer the queries in the following way: - The largest number that is smaller or equal than 2 in the tree is 2, and the smallest number that is greater or equal than 2 is still 2. So the answer for the first query is [2,2]. - The largest number that is smaller or equal than 5 in the tree is 4, and the smallest number that is greater or equal than 5 is 6. So the answer for the second query is [4,6]. - The largest number that is smaller or equal than 16 in the tree is 15, and the smallest number that is greater or equal than 16 does not exist. So the answer for the third query is [15,-1].
Example 2:
Input: root = [4,null,9], queries = [3] Output: [[-1,4]] Explanation: The largest number that is smaller or equal to 3 in the tree does not exist, and the smallest number that is greater or equal to 3 is 4. So the answer for the query is [-1,4].
Constraints:
[2, 105].1 <= Node.val <= 106n == queries.length1 <= n <= 1051 <= queries[i] <= 106Problem summary: 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 a such value does not exist, add -1 instead. maxi is the smallest value in the tree that is greater than or equal to queries[i]. If a such value does not exist, add -1 instead. Return the array answer.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Binary Search · Tree
[6,2,13,1,4,9,15,null,null,null,null,null,null,14] [2,5,16]
[4,null,9] [3]
closest-binary-search-tree-value)closest-binary-search-tree-value-ii)search-in-a-binary-search-tree)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #2476: Closest Nodes Queries in a Binary Search Tree
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private List<Integer> nums = new ArrayList<>();
public List<List<Integer>> closestNodes(TreeNode root, List<Integer> queries) {
dfs(root);
List<List<Integer>> ans = new ArrayList<>();
for (int x : queries) {
int i = Collections.binarySearch(nums, x + 1);
int j = Collections.binarySearch(nums, x);
i = i < 0 ? -i - 2 : i - 1;
j = j < 0 ? -j - 1 : j;
int mi = i >= 0 && i < nums.size() ? nums.get(i) : -1;
int mx = j >= 0 && j < nums.size() ? nums.get(j) : -1;
ans.add(List.of(mi, mx));
}
return ans;
}
private void dfs(TreeNode root) {
if (root == null) {
return;
}
dfs(root.left);
nums.add(root.val);
dfs(root.right);
}
}
// Accepted solution for LeetCode #2476: Closest Nodes Queries in a Binary Search Tree
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
func closestNodes(root *TreeNode, queries []int) (ans [][]int) {
nums := []int{}
var dfs func(*TreeNode)
dfs = func(root *TreeNode) {
if root == nil {
return
}
dfs(root.Left)
nums = append(nums, root.Val)
dfs(root.Right)
}
dfs(root)
for _, x := range queries {
i := sort.SearchInts(nums, x+1) - 1
j := sort.SearchInts(nums, x)
mi, mx := -1, -1
if i >= 0 {
mi = nums[i]
}
if j < len(nums) {
mx = nums[j]
}
ans = append(ans, []int{mi, mx})
}
return
}
# Accepted solution for LeetCode #2476: Closest Nodes Queries in a Binary Search Tree
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def closestNodes(
self, root: Optional[TreeNode], queries: List[int]
) -> List[List[int]]:
def dfs(root: Optional[TreeNode]):
if root is None:
return
dfs(root.left)
nums.append(root.val)
dfs(root.right)
nums = []
dfs(root)
ans = []
for x in queries:
i = bisect_left(nums, x + 1) - 1
j = bisect_left(nums, x)
mi = nums[i] if 0 <= i < len(nums) else -1
mx = nums[j] if 0 <= j < len(nums) else -1
ans.append([mi, mx])
return ans
// Accepted solution for LeetCode #2476: Closest Nodes Queries in a Binary Search Tree
/**
* [2476] Closest Nodes Queries in a Binary Search Tree
*/
pub struct Solution {}
use surf::url::UrlQuery;
use crate::util::tree::{to_tree, TreeNode};
// submission codes start here
// Definition for a binary tree node.
// #[derive(Debug, PartialEq, Eq)]
// pub struct TreeNode {
// pub val: i32,
// pub left: Option<Rc<RefCell<TreeNode>>>,
// pub right: Option<Rc<RefCell<TreeNode>>>,
// }
//
// impl TreeNode {
// #[inline]
// pub fn new(val: i32) -> Self {
// TreeNode {
// val,
// left: None,
// right: None
// }
// }
// }
use std::cell::RefCell;
use std::rc::Rc;
impl Solution {
pub fn closest_nodes(root: Option<Rc<RefCell<TreeNode>>>, queries: Vec<i32>) -> Vec<Vec<i32>> {
let mut array = Vec::new();
let mut stack = Vec::new();
let mut root = root;
while root.is_some() || !stack.is_empty() {
while let Some(r) = root {
stack.push(Rc::clone(&r));
root = r.borrow().left.clone();
}
root = stack.pop();
if let Some(r) = root {
array.push(r.borrow().val);
root = r.borrow().right.clone();
}
}
let mut result = Vec::with_capacity(queries.len());
for query in queries {
let pos = array.binary_search(&query);
match pos {
Ok(pos) => {
result.push(vec![array[pos], array[pos]]);
}
Err(pos) => {
if pos == 0 {
result.push(vec![-1, array[pos]]);
} else if pos == array.len() {
result.push(vec![array[pos - 1], -1])
} else {
result.push(vec![array[pos - 1], array[pos]]);
}
}
}
}
result
}
}
// submission codes end
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_2476() {}
}
// Accepted solution for LeetCode #2476: Closest Nodes Queries in a Binary Search Tree
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function closestNodes(root: TreeNode | null, queries: number[]): number[][] {
const nums: number[] = [];
const dfs = (root: TreeNode | null) => {
if (!root) {
return;
}
dfs(root.left);
nums.push(root.val);
dfs(root.right);
};
const search = (x: number): number => {
let [l, r] = [0, nums.length];
while (l < r) {
const mid = (l + r) >> 1;
if (nums[mid] >= x) {
r = mid;
} else {
l = mid + 1;
}
}
return l;
};
dfs(root);
const ans: number[][] = [];
for (const x of queries) {
const i = search(x + 1) - 1;
const j = search(x);
const mi = i >= 0 ? nums[i] : -1;
const mx = j < nums.length ? nums[j] : -1;
ans.push([mi, mx]);
}
return ans;
}
Use this to step through a reusable interview workflow for this problem.
Check every element from left to right until we find the target or exhaust the array. Each comparison is O(1), and we may visit all n elements, giving O(n). No extra space needed.
Each comparison eliminates half the remaining search space. After k comparisons, the space is n/2ᵏ. We stop when the space is 1, so k = log₂ n. No extra memory needed — just two pointers (lo, hi).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Setting `lo = mid` or `hi = mid` can stall and create an infinite loop.
Usually fails on: Two-element ranges never converge.
Fix: Use `lo = mid + 1` or `hi = mid - 1` where appropriate.
Wrong move: Recursive traversal assumes children always exist.
Usually fails on: Leaf nodes throw errors or create wrong depth/path values.
Fix: Handle null/base cases before recursive transitions.