Closest Binary Search Tree Value - Problem

Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target.

If there are multiple values with the same minimum difference, return the smallest value.

Example:

For BST [4,2,5,1,3] and target 3.714286, the closest value is 4.

Input & Output

Example 1 — Basic BST
$ Input: root = [4,2,5,1,3], target = 3.714286
Output: 4
💡 Note: The differences are: |4-3.714286|=0.286, |2-3.714286|=1.714, |5-3.714286|=1.286, |1-3.714286|=2.714, |3-3.714286|=0.714. The closest value is 4.
Example 2 — Exact Match
$ Input: root = [1,null,2], target = 2.0
Output: 2
💡 Note: Target 2.0 exactly matches node value 2, so return 2.
Example 3 — Tie Breaker
$ Input: root = [1,null,3], target = 2.0
Output: 1
💡 Note: |1-2|=1 and |3-2|=1. Both have same distance, return smaller value 1.

Constraints

  • The number of nodes in the tree is in the range [1, 104]
  • 0 ≤ Node.val ≤ 109
  • -109 ≤ target ≤ 109

Visualization

Tap to expand
Closest BST Value: Target = 3.71442513Distances:|4-3.714| = 0.286 ✓|2-3.714| = 1.714|5-3.714| = 1.286|1-3.714| = 2.714|3-3.714| = 0.714Output: 4 (minimum distance)
Understanding the Visualization
1
Input BST
Binary search tree [4,2,5,1,3] with target = 3.714
2
Calculate Distances
Find absolute differences: |4-3.714|, |2-3.714|, etc.
3
Return Closest
Node 4 has minimum distance of 0.286
Key Takeaway
🎯 Key Insight: Use BST property to navigate efficiently towards target while tracking closest value
Asked in
Google 15 Facebook 12 Amazon 8 Microsoft 6
58.2K Views
Medium Frequency
~15 min Avg. Time
2.2K 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