Junior

Closest Binary Search Tree Value

Given the root of a binary search tree and a floating-point value target, return the value in the BST that is closest to target.

A binary search tree satisfies the property that for every node:

  • All values in its left subtree are less than the node's value.
  • All values in its right subtree are greater than the node's value.

You may assume there is exactly one value in the tree that is closest to target.

Example 1
        4
       / \
      2   5
     / \
    1   3
Inputroot = [4,2,5,1,3], target = 3.714286
Output4
The value 4 is closer to 3.714286 than any other value in the tree.
Example 2
        1
Inputroot = [1], target = 4.428571
Output1
The tree contains only the value 1, so it is the closest value to the target.

Constraints

  • The number of nodes in the tree is in the range [1, 10^4]
  • 0 <= Node.val <= 10^9
  • -10^9 <= target <= 10^9

Asked at 9 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate