Find the Closest Value in a Binary Search Tree
A binary search tree is supplied in level-order form, using null for a missing child. Find the stored integer whose numeric value is closest to a floating-point target. Use the BST ordering rather than requiring a full traversal.
Function Signature
closest_bst_value(tree: list[int | null], target: float) -> int
Valid Input Domain
The list encodes one nonempty valid BST with unique integer values. Null entries denote absent children. Inputs guarantee exactly one closest stored value.
Exact Output Semantics
Return the unique integer value minimizing absolute(value - target). Because the valid domain guarantees uniqueness, no tie-break is needed.
Constraints
-
1 <= number of non-null nodes <= 100,000.
-
-10^9 <= node value <= 10^9.
-
-10^9 <= target <= 10^9.
-
The tree representation contains no unreachable non-null entries.
Public Examples
Example 1
Input: tree = [4, 2, 5, 1, 3], target = 3.714
Output: 4
Four is closer to 3.714 than any other stored value.
Example 2
Input: tree = [2, 1, 3], target = 1.2
Output: 1
One is the unique closest value.
Hints
-
At every visited node, compare its value with both the current best and the target.
-
The BST ordering tells you which unexplored side can still contain a closer value.