Closest Binary Search Tree Value II

Given the root of a binary search tree, a target value, and an integer k, return the k values in the tree that are closest to the target. Pattern focus: BST Range Bounds. Maintain the closest candidates around the target while relying on the BST ordering to prune values that are clearly farther away.

Input Format

root = binary tree root, target = decimal target value, k = number of closest values

Output Format

array of k closest values in ascending order

Constraints

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

Examples

Example 1:

Input:

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

Output:

[3,4]

Explanation:

The two closest values to 3.714286 are 4 and 3.

Example 2:

Input:

root = [4,2,5,1,3]
target = 0
k = 3

Output:

[1,2,3]

Explanation:

The three closest values to 0 are the three smallest values in the tree.

Loading...
Closest Binary Search Tree Value II