Given the root of a binary search tree and a target value, return the value in the BST that is closest to the target. If multiple values are equally close, return the smallest such value.
A binary search tree satisfies: the left subtree of every node contains only keys less than the node's key, the right subtree contains only keys greater than the node's key, and both subtrees are themselves BSTs.
The tree is provided as a level-order (breadth-first) array root, where index 0 is the root and the children of the node at index i are at indices 2*i + 1 and 2*i + 2. Because it is a BST, you can walk down from the root toward target in O(height) time, tracking the closest value seen and preferring the smaller value on ties.
Examples
01 · Example 1
root = [4, 2, 5, 1, 3] target = 3.714286 return = 4
|4 - 3.714286| = 0.286 is smaller than |3 - 3.714286| = 0.714, so 4 is closest.
02 · Example 2
root = [1] target = 4.428571 return = 1
The tree has a single node, so 1 is the only and therefore closest value.
03 · Example 3
root = [2, 1, 3] target = 2.5 return = 2
Both 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.
More Roblox problems
- Candy Crush Grid Matching and GravityPHONE SCREEN · Seen Jun 2026
- Design Search Autocomplete SystemPHONE SCREEN · Seen Jun 2026
- Find the Closest PalindromePHONE SCREEN · Seen Jun 2026
- Grid Pathfinding with Obstacles (DFS)PHONE SCREEN · Seen Jun 2026
- Maximize Distance to Closest PersonPHONE SCREEN · Seen Jun 2026
- Maximum Number of Balls in a BoxPHONE SCREEN · Seen Jun 2026
- Meeting Rooms IIPHONE SCREEN · Seen Jun 2026
- Most Frequent Call Path From Function Trace LogsPHONE SCREEN · Seen Jun 2026
public int closestValue(int[] root, float target) {
// write your code here
}root[4, 2, 5, 1, 3]
target3.714286
expected4
sign in to submit