← Questions
Closest binary search tree value
0
I was asked this
No reports yet. Sign in to say where you were asked it.
A coding interview question asked in Meta's AI-enabled coding round, last asked Jul 2025. It tests binary search tree.
Given the root of a binary search tree and a target number, which may be fractional, return the value in the tree closest to the target. Walk down a single path from the root rather than visiting every node.
Interface
Unless you agree on a different interface with the interviewer, assume:
-
closest_value(root: TreeNode, target: float) -> int— the tree has at least one node and distinct values. If two values are equally close, return the smaller one.
Example
tree: 4
/ \
2 5
/ \
1 3
closest_value(root, 3.714286) -> 4
closest_value(root, 3.5) -> 3 # 3 and 4 tie; the smaller wins
closest_value(root, 0.2) -> 1
Constraints
-
1 <= number of nodes <= 10^4; node values fit in 32-bit integers; the target is a float. - The tree may be unbalanced, so the path can be as long as the tree.
Clarifying questions
- Can the target be fractional or outside the range of the tree?
- How are ties broken?
- Is the tree balanced, or should I assume it can be a chain?
What a strong answer covers
- Start at the root, track the best value seen, and go left or right by comparing the target with the node; every node on the path is a candidate.
O(h)time,O(1)space when iterative. - Why the closest value must lie on that path (the BST ordering rules out the other subtree).
- Careful comparison of distances, including the tie rule.
- Tests: target equal to a node, below the minimum, above the maximum, a chain-shaped tree.
Follow-ups
- Return the
kvalues closest to the target (in-order traversal with a window or two stacks,O(h + k)). - The tree changes often. What stays efficient?
- Return the closest value strictly smaller than the target (the predecessor).
Where it's asked
- Meta · AI-enabled coding · Last asked Jul 202560 min · Several progressive tasks on a starter codebase in CoderPad with an AI assistant panel; usually two rounds · The first task usually without AI, later tasks with it
What it tests
binary search tree
No official answer yet. Write yours on the right and run it.
Nothing published yet.
Sign in to submit your code; every attempt is kept here.
Write and test your solution herePython in your browser, the question's tests level by level, every submission kept for you.Sign in to start coding
