Problem · Tree
Closest Binary Search Tree Value — Base Practice
Learn this problemProblem statement
You are given a binary search tree and a target value. Return the value in the tree whose absolute difference from target is smallest. If two values are equally close, return the smaller value.
For this executable base exercise, the tree is supplied as a fully populated level-order array root: the children of index i are at 2 * i + 1 and 2 * i + 2 when those indices exist.
Use the binary-search-tree ordering to walk toward the target while tracking the best value seen.
Function
closestValue(root: int[], target: float) → intExamples
Example 1
root = [4, 2, 5, 1, 3]target = 3.714286return = 4|4 - 3.714286| = 0.286 is smaller than |3 - 3.714286| = 0.714, so 4 is closest.
Example 2
root = [1]target = 4.428571return = 1The tree has a single node, so 1 is the only and therefore closest value.
Example 3
root = [2, 1, 3]target = 2.5return = 2Both 2 and 3 are 0.5 away from 2.5. Return the smaller value, 2.
Constraints
1 <= number of nodes <= 10^40 <= Node.val <= 10^9-10^9 <= target <= 10^9- The input array is a level-order serialization of a valid binary search tree.