Closest Binary Search Tree Value II - Problem
You're given the root of a binary search tree, a target value, and an integer k. Your task is to find the k values in the BST that are closest to the target.
Think of it as finding your k nearest neighbors in a sorted tree structure! The beauty of this problem lies in leveraging the BST's sorted property to efficiently locate the closest values without examining every single node.
Key Points:
- You may return the answer in any order
- You're guaranteed to have exactly one unique set of k closest values
- "Closest" means smallest absolute difference:
|node.val - target|
Example: If target=3.714286 and k=2 in BST [4,2,5,1,3], the two closest values are [4,3] since |4-3.714286|=0.285714 and |3-3.714286|=0.714286 are the smallest differences.
Input & Output
example_1.py — Basic Case
$
Input:
root = [4,2,5,1,3], target = 3.714286, k = 2
›
Output:
[4,3]
💡 Note:
The node values in the BST are [1,2,3,4,5]. The distances to target 3.714286 are: |1-3.714286|=2.714286, |2-3.714286|=1.714286, |3-3.714286|=0.714286, |4-3.714286|=0.285714, |5-3.714286|=1.285714. The 2 closest values are 4 and 3.
example_2.py — Single Node
$
Input:
root = [1], target = 0.000000, k = 1
›
Output:
[1]
💡 Note:
There's only one node in the BST, so we return its value. Distance is |1-0|=1.
example_3.py — All Nodes Required
$
Input:
root = [3,1,4,null,2], target = 2.5, k = 4
›
Output:
[2,3,1,4]
💡 Note:
All nodes in the BST are [1,2,3,4]. Distances to target 2.5: |1-2.5|=1.5, |2-2.5|=0.5, |3-2.5|=0.5, |4-2.5|=1.5. Since k=4, we return all nodes. Note that 2 and 3 are equidistant, so either ordering is acceptable.
Constraints
- The number of nodes in the tree is n where 1 ≤ n ≤ 104
- 0 ≤ Node.val ≤ 109
- -109 ≤ target ≤ 109
- 1 ≤ k ≤ n
- It's guaranteed that there is only one unique set of k values in the BST that are closest to the target
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code