Roblox
Closest Binary Search Tree Value
Coding
Problem
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 there are multiple answers, return the smallest such value.
A binary search tree satisfies these constraints:
- The left subtree of every node contains only nodes with keys less than the node's key.
- The right subtree of every node contains only nodes with keys greater than the node's key.
- Both the left and right subtrees are also BSTs.
Examples
Example 1:
Input: root = [4,2,5,1,3], target = 3.714286
Output: 4
Explanation:
|4 - 3.714| = 0.286 is smaller than |3 - 3.714| = 0.714.
Example 2:
Input: root = [1], target = 4.428571
Output: 1
Example 3:
Input: root = [2,1,3], target = 2.5
Output: 2
Explanation:
Both 2 and 3 are 0.5 away from 2.5; return the smaller value.
Constraints
1 <= number of nodes <= 10^40 <= Node.val <= 10^9-10^9 <= target <= 10^9
Solution
Loading editor…
Sign in to get AI feedback on your answer. Your work is saved while you do.
Sign in to evaluate