Find the Stored Value Nearest to a Number
Implement closestValue
You are given the root of a binary search tree with distinct values and an integer target. Return the value in the tree that is closest to target — the one with the smallest absolute difference. If two values are equally close, return the smaller one. If the tree is empty, return -1.
Comparing against every value works. Since the nearest value must lie along the search path for the target, one walk from the root is enough.
Example 1:
Input: root = [50,30,70,20,40,60,80,null,null,35,45], target = 43
Output: 45
Example 2:
Input: root = [50,30,70,20,40,60,80,null,null,35,45], target = 55
Output: 50
Example 3:
Input: root = [50,30,70,20,40,60,80,null,null,35,45], target = 1000
Output: 80
+ 14 hidden test cases run on Submit.
Constraints:
- ●
0 ≤ number of nodes ≤ 100; all node values are distinct, 0 ≤ node.val ≤ 1000 - ●
The tree is a binary search tree (left subtree smaller, right subtree larger at every node), given by its root node - ●
0 ≤ target ≤ 1000 (an integer that need not be in the tree) - ●
Return the tree value whose distance |value − target| is smallest. If two values are equally close, return the smaller one. An empty tree gives -1
root =
target =