HardTwo PointersStackTreeDepth-First SearchBinary Search TreeHeapBinary TreeUpdated Sep 2026

272. Closest Binary Search Tree Value II

Asked at LinkedIn

Difficulty

Hard

Time

O(n)

Space

O(h + k)

Pattern

Two Pointers

Companies

1

Problem

You are given the root of a binary search tree (BST), a target number target (it may have a fractional part), and an integer k. Return the k values in the tree that are closest to target.

"Closest" means smallest absolute difference: abs(value - target). The answer may be in any order. The problem guarantees that there is exactly one set of k values that is closest, so you never have to break a tie.

A BST has a useful property: if you read its values from left to right (an inorder traversal), they come out in sorted order. So the k closest values always sit next to each other in that sorted list — they form a window of size k.

Pick the k nearest values

123dist 0.714dist 0.295target = 3.714286, k = 2inorderk = 21234501234The k closest values form one contiguous window insorted order
Inorder gives sorted values, and the two closest to 3.714286 are 3 and 4.

Constraints

  • ●1 <= k <= n <= 10^4, where n is the number of nodes
  • ●0 <= Node.val <= 10^9
  • ●-10^9 <= target <= 10^9

Examples

Example 1
Inputroot = [4,2,5,1,3], target = 3.714286, k = 2
Output[4,3]
WhyThe sorted values are 1,2,3,4,5. Distances to 3.714286 are 2.71, 1.71, 0.71, 0.29, 1.29. The two smallest are 0.29 (value 4) and 0.71 (value 3).
Example 2
Inputroot = [1], target = 0.000000, k = 1
Output[1]
WhyThe tree has only one value, so it must be the answer.

Asked At

1 companies
CompanyDifficulty
LinkedInHardView all LinkedIn questions →

How to Think About It

1

Simple approach: collect all values, sort by abs(v - target), take k. That is O(n log n) and ignores the BST ordering entirely.

2

Key insight: an inorder traversal visits values in sorted order, and the k closest values to any target form a contiguous window in that sorted order.

3

Maintain a deque of at most k values during the inorder walk. When it is full and the new value is closer than the leftmost one, drop the leftmost and append the new one. When the new value is not closer, stop — every later value is even farther away.

4

Walkthrough for [4,2,5,1,3], target 3.714286, k 2: inorder 1,2,3,4,5. Window fills with [1,2]; 3 is closer than 1 -> [2,3]; 4 is closer than 2 -> [3,4]; 5 is not closer than 3 -> stop. Answer [3,4].

5

Follow-up: the tree is balanced and you want better than O(n). Use two stacks (predecessors and successors) seeded by searching for the target, then merge like two pointers in O(k + log n).

Optimal Approach

Step 1: Do an inorder traversal (iteratively or recursively).
Step 2: For each visited value v:
If the deque has fewer than k values: append v.
Else if abs(v - target) < abs(dq[0] - target): pop left, append v.
Else: stop the traversal.
Step 3: Return the deque contents.

The early stop is valid because values only get larger (and farther from the target) after this point.

Time: O(n) worst case. Space: O(h + k).

Sliding window during inorder

inorder[1,2]1234501234v=2Step 1 — the window fills up with 1 and 2inorder[2,3]1234501234v=3Step 2 — 3 is closer than 1, so drop 1 and add 3inorder[3,4]1234501234v=4Step 3 — 4 is closer than 2, so drop 2 and add 4v = 5: abs(5−t) > abs(3−t)later values only get fartherstop and return [3,4]
Keep at most k values. Replace the leftmost only when the new value is strictly closer; otherwise stop.
ComplexityTime O(n)Space O(h + k)In the worst case the inorder walk visits every node; h is the tree height for the traversal stack, and the deque holds at most k values.

What Trips People Up in Real Interviews

1

Sorting all values by distance. It works but throws away the BST ordering the interviewer gave you on purpose.

2

Using a max-heap of size k with no early exit. It is O(n log k) — fine, but mention the sorted-window argument that allows stopping early.

3

Comparing with the wrong end of the window. Values arrive in increasing order, so the value to evict is always the leftmost (smallest).

4

Integer-casting the target. The target is a double; keep distance comparisons in floating point.

Solution Code

O(n) time
from collections import deque

def closestKValues(root, target, k):
    dq = deque()
    stack = []
    node = root
    while stack or node:
        while node:
            stack.append(node)
            node = node.left
        node = stack.pop()
        v = node.val
        if len(dq) < k:
            dq.append(v)
        elif abs(v - target) < abs(dq[0] - target):
            dq.popleft()
            dq.append(v)
        else:
            break
        node = node.right
    return list(dq)

Pro at DSA?

Test your skills with a real FAANG-style mock interview.

Start a Mock Interview →

Frequently Asked Questions

What is the Closest Binary Search Tree Value II problem?

Closest Binary Search Tree Value II asks for the `k` values in a BST that are closest to a (possibly fractional) target. The BST property gives you the values in sorted order for free, which turns the problem into finding the best window of size `k` in a sorted sequence.

How do you solve Closest Binary Search Tree Value II?

The optimal approach runs in O(n) time and O(h + k) space. Scroll up to "Optimal Approach" for the step-by-step walkthrough, diagrams, and code in Python, C++ and Java.

What companies ask Closest Binary Search Tree Value II?

Closest Binary Search Tree Value II is asked at LinkedIn. It is a hard difficulty problem.

What are common mistakes on Closest Binary Search Tree Value II?
  • Sorting all values by distance. It works but throws away the BST ordering the interviewer gave you on purpose.
  • Using a max-heap of size k with no early exit. It is `O(n log k)` — fine, but mention the sorted-window argument that allows stopping early.
  • Comparing with the wrong end of the window. Values arrive in increasing order, so the value to evict is always the leftmost (smallest).
  • Integer-casting the target. The target is a double; keep distance comparisons in floating point.