Closest Binary Search Tree Value - Problem
Given the root of a binary search tree and a target value, find the value in the BST that is closest to the target.

The goal is to minimize the absolute difference between any node's value and the target. If there are multiple nodes with the same minimum distance, return the smallest value.

Example: If your BST contains values [1, 3, 6, 8] and target is 4.5, both 3 and 6 are distance 1.5 away, so return 3 (the smaller value).

Input & Output

example_1.py โ€” Basic Case
$ Input: root = [4,2,6,1,3], target = 3.714286
โ€บ Output: 4
๐Ÿ’ก Note: The values 3 and 4 are both close to the target. Distance from 3: |3 - 3.714286| = 0.714286. Distance from 4: |4 - 3.714286| = 0.285714. Since 4 is closer, we return 4.
example_2.py โ€” Tie Breaking
$ Input: root = [1,null,3], target = 2.0
โ€บ Output: 1
๐Ÿ’ก Note: Both 1 and 3 are exactly distance 1.0 from target 2.0. According to the problem, we return the smaller value, which is 1.
example_3.py โ€” Single Node
$ Input: root = [5], target = 7.5
โ€บ Output: 5
๐Ÿ’ก Note: Tree contains only one node with value 5, so that must be the closest value regardless of target.

Visualization

Tap to expand
Binary Search Tree: Smart Navigation426137๐ŸŽฏ Target: 3.73.7 < 4 โ†’ GO LEFT3.7 > 2 โ†’ GO RIGHT๐Ÿ“Š Distance Analysis|4 - 3.7| = 0.3|2 - 3.7| = 1.7|3 - 3.7| = 0.7Answer: 4 (closest)โšก EfficiencyVisited: 3 nodes onlyPath: 4 โ†’ 2 โ†’ 3Time: O(height)vs O(n) brute force!
Understanding the Visualization
1
Start Journey
Begin at the root node (city center) and set it as current closest
2
Smart Navigation
At each intersection, choose direction based on target: left for smaller values, right for larger
3
Track Best Option
Update closest value whenever we find a better candidate during our journey
4
Efficient Path
Reach the answer in O(height) steps instead of visiting every node
Key Takeaway
๐ŸŽฏ Key Insight: BST property eliminates half the search space at each step, making this problem solvable in O(log n) time for balanced trees - much better than checking every node!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Must visit all n nodes in the tree to ensure we find the closest value

n
2n
โœ“ Linear Growth
Space Complexity
O(h)

Recursion stack depth equals tree height h, which can be O(n) in worst case

n
2n
โœ“ Linear Space

Constraints

  • The number of nodes in the tree is in the range [1, 104]
  • 0 โ‰ค Node.val โ‰ค 109
  • -109 โ‰ค target โ‰ค 109
  • It's guaranteed that there will be only one unique value closest to the target
Asked in
Google 45 Amazon 38 Facebook 25 Microsoft 22
67.2K Views
High Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen