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.
Visualization
Tap to expand
Understanding the Visualization
1
Inorder Traversal
Walk through the BST in sorted order to get [1, 2, 3, 4, 5]
2
Find Insertion Point
Locate where target 3.714 would fit: between 3 and 4
3
Expand with Two Pointers
Compare distances: |4-3.714|=0.286 vs |3-3.714|=0.714
4
Collect K Closest
Choose the k=2 values with smallest distances: [4, 3]
Key Takeaway
๐ฏ Key Insight: Use the BST's sorted property via inorder traversal, then apply two pointers from the insertion point to efficiently find the k closest values in O(n) time.
Time & Space Complexity
Time Complexity
O(n)
O(n) for inorder traversal + O(log n) for binary search + O(k) for two pointers
โ Linear Growth
Space Complexity
O(n)
O(n) to store all values in array
โก Linearithmic Space
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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code