This problem is common in MAANG-style interviews because it checks whether you can use a data structure’s ordering (BST invariants) to prune search, reason about comparisons with real numbers, and implement a precise tie-breaker condition instead of brute-forcing all nodes.
Problem statement
You’re given the root of a Binary Search Tree (BST) and a real number target. Return the value in the BST that is closest to the target. If there is more than one answer, print the smallest.
Constraints:
- The number of nodes in the tree is in the range [1, 104].
- 0 <=
Node.val<= 109 - -109 <=
target<= 109
Examples
Optimized approach using Binary Search Tree property
We do not need to scan the entire tree to find the value closest to the target. The key reason is the binary search tree property: values in the left subtree are smaller than the current node, and values in the right subtree are larger. This lets us decide which direction can still contain a better answer.
If the target is smaller than the current node’s value, then any value closer to the target must be in the left subtree, because every value in the right subtree is even larger and will generally be farther from a smaller target. Similarly, if the target is greater than or equal to the current node’s value, then any value closer to the target must be in the right subtree, because every value in the left subtree is smaller and will generally be farther from a larger target.
So the algorithm is a guided walk down one root-to-leaf path: at each node, update the best candidate if this node is closer to the target than the current best. If two values are equally close, apply a consistent tie-break rule, return the smaller value. This keeps the search efficient while still guaranteeing correctness.
Step-by-step algorithm
Here are the algorithm steps of the solution:
- Initialize
closestwith the root node’s value. - While
rootis notNone:- Compare
current.datawithclosest:- If
current.datais closer totargetthanclosest, updateclosest. - If both are equally close, keep the smaller value.
- If
- Move in the BST based on the target:
- If
target < current.data, setcurrent = current.left. - Otherwise, set
current = current.right.
- If
- Compare
- When the entire tree is traversed, return
closest.
Take a look at the illustration below to understand the solution more clearly.
Code implementation in Python
Now, let’s look at the Python code for the optimized solution discussed above.
Code for the closest binary search tree value problem
Time complexity
The time complexity for this solution is O(H), where H is the height of the tree. As we are using the properties of a Binary Search Tree, we do not need to visit every node; instead, we follow a single path from the root down to a leaf.
Space complexity
The space complexity for this solution is constant, O(1) because the algorithm is iterative rather than recursive, it does not use a call stack. We only maintain a few variables to track our progress, so the amount of memory used remains the same regardless of how large the tree grows.
Common mistakes
To ensure a high-quality implementation, be mindful of these common pitfalls and technical nuances that candidates often encounter during interviews.
- Forgetting the tie-breaker: A common error is failing to return the smaller value when two nodes are equally close to the target.
- Ignoring the BST Property: Avoid using a full Tree Traversal (BFS/DFS) which takes O(N) time; use the binary search logic to achieve O(H) time.
- Recursive space overhead: Using recursion adds O(H) to the space complexity due to the call stack; the iterative approach is superior as it uses O(1) space.
- Early exit opportunity: If you encounter a node value exactly equal to the target, return it immediately to save unnecessary iterations.
- Initial closest value: Do not initialize your tracking variable with 0 or a large constant; always initialize it with the
rootvalue to ensure it is a valid node from the start. - Balanced vs. skewed Trees: In interviews, always clarify that while the average time complexity is O(log N), it degrades to O(N) if the tree is skewed (like a linked list).