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 Binary Search Tree Value INPUT Binary Search Tree 4 2 5 1 3 root = [4,2,5,1,3] target = 3.714286 Target: 3.714286 ~target ALGORITHM STEPS 1 Start at Root Initialize closest = 4 diff = |4-3.71| = 0.29 2 BST Navigation 3.71 < 4, go LEFT to 2 |2-3.71| = 1.71 > 0.29 3 Continue Search 3.71 > 2, go RIGHT to 3 |3-3.71| = 0.71 > 0.29 4 Leaf Reached Node 3 has no right child Search complete! Distance Comparison Node Difference 4 0.29 (min) 3 0.71 FINAL RESULT Closest Node Highlighted 4 CLOSEST! 2 5 1 3 Output: 4 Min distance: 0.286 OK - Verified! Key Insight: BST property enables O(h) time complexity: at each node, compare difference and traverse LEFT if target < node.val, else RIGHT. No need to explore entire tree! Time: O(h) where h = tree height | Space: O(1) iterative or O(h) recursive TutorialsPoint - Closest Binary Search Tree Value | Optimal Solution
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