You are given the root of a binary search tree (BST) and a floating-point number target.
Return the value stored in the tree that is closest to target, where closeness is measured by absolute difference. If two different node values are equally close to the target, return the smaller of the two values.
Example 1
Input: root = [4,2,5,1,3], target = 3.714286
Output: 4
Among the values, 4 is nearest to 3.714286 (distance about 0.286), closer than 3 (distance about 0.714).
Example 2
Input: root = [1], target = 4.428571
Output: 1
The tree holds only the value 1, so it is trivially the closest to the target.
Constraints
The number of nodes in the tree is in the range [1, 10^4].0 <= Node.val <= 10^9-10^9 <= target <= 10^9See the step-by-step animation, the intuition, and clean code in every language — free, no credit card.
FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.
750+ engineers trained · frontend, backend, AWS & AI