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
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
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
โ Linear Growth
Space Complexity
O(h)
Recursion stack depth equals tree height h, which can be O(n) in worst case
โ 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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code