Junior
Closest Binary Search Tree Value
Given the root of a binary search tree and a floating-point value target, return the value in the BST that is closest to target.
A binary search tree satisfies the property that for every node:
- All values in its left subtree are less than the node's value.
- All values in its right subtree are greater than the node's value.
You may assume there is exactly one value in the tree that is closest to target.
Example 1
4
/ \
2 5
/ \
1 3Input
root = [4,2,5,1,3], target = 3.714286Output
4The value 4 is closer to 3.714286 than any other value in the tree.
Example 2
1
Input
root = [1], target = 4.428571Output
1The tree contains only the value 1, so it is the closest value 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^9