Closest Binary Search Tree Value

Given the root of a binary search tree and a target value, return the value in the tree that is closest to the target. Pattern focus: BST Search. Use the BST ordering to prune the search path while maintaining the best answer seen so far.

Input Format

root = binary tree root, target = decimal target value

Output Format

closest integer value present in the BST

Constraints

  • 1 <= number of nodes <= 10^5
  • -10^9 <= node values <= 10^9
  • 0.0 <= target <= 10^9.0
  • root and target must satisfy the format described in inputFormat.

Examples

Example 1:

Input:

root = [4,2,5,1,3]
target = 3.714286

Output:

4

Explanation:

4 is closer to 3.714286 than 3.

Example 2:

Input:

root = [4,2,5,1,3]
target = 1.2

Output:

1

Explanation:

1 is the closest value to 1.2.

Loading...
Closest Binary Search Tree Value