You are given a binary search tree and a real number target. Return the value stored in the tree that is closest to target. If two values are equally close, return the smaller one.
Function Signature
def closest_value(tree: list[int | None], target: float) -> int:
Rules
-
tree
lists the nodes in level order, with
None
for a missing child. Children of a missing node are not listed, so
[4, 2, 5, 1, 3]
is the tree in the first example and
[2, None, 3]
is a root 2 with only a right child 3.
-
The tree is a valid binary search tree: every value in a node's left subtree is smaller than the node's value, and every value in its right subtree is larger.
-
Distance is the absolute difference
abs(value - target)
. When two values are at the same distance, the smaller value is the answer.
Constraints
-
The number of nodes is in the range
[1, 10^4]
.
-
0 <= Node.val <= 10^9
-
-10^9 <= target <= 10^9
Examples
Input: tree = [4, 2, 5, 1, 3], target = 3.714286
Output: 4
The root is 4 with children 2 and 5, and 2 has children 1 and 3. The value 4 is 0.285714 away from the target and 3 is 0.714286 away, so 4 is the closest.
Input: tree = [1], target = 4.428571
Output: 1
The tree has a single node, so its value is the answer no matter how far away the target is.
Input: tree = [4, 2, 5, 1, 3], target = 3.5
Output: 3
Both 3 and 4 are 0.5 away from the target. The tie goes to the smaller value, 3.