Closest Binary Search Tree Value II
The problem
Given the root of a binary search tree, a target value, and an integer k, return the k values in the BST that are closest to the target. You may return the answer in any order. You are guaranteed to have only one unique set of k values in the BST that are closest to the target.
Input: root = [4,2,5,1,3], target = 3.714286, k = 2 Output: [4,3]
Input: root = [1], target = 0.000000, k = 1 Output: [1]
Input: root = [1], target = 0.000000, k = 1
- The number of nodes in the tree is n.
- 1 <= k <= n <= 104.
- 0 <= Node.val <= 109
- -109 <= target <= 109
cpp
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector<int> closestKValues(TreeNode* root, double target, int k) {
}
};java
class Solution {
public void dfs(TreeNode node, Deque<Integer> dq, int k, double target) {
if (node == null) return;
dfs(node.left, dq, k, target);
dq.addLast(node.val);
if (dq.size() > k) {
if (Math.abs(target - dq.peekFirst()) <= Math.abs(target - dq.peekLast())) {
dq.pollLast();
return;
} else {
dq.pollFirst();
}
}
dfs(node.right, dq, k, target);
}
public List<Integer> closestKValues(TreeNode root, double target, int k) {
// Your code goes here
Deque<Integer> dq = new LinkedList<>();
dfs(root, dq, k, target);
return new ArrayList<>(dq);
}
}python
class Solution:
def closestKValues(self, root, target, k):
# Your code goes herejavascript
class Solution {
closestKValues(root, target, k) {
// Your code goes here
}
}csharp
public class Solution {
public IList<int> ClosestKValues(TreeNode root, double target, int k) {
// Your code goes here
}
}go
/*
Definition for a binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
*/
func closestKValues(root *TreeNode, target float64, k int) []int {
}Stuck? Show a way to structure it+
- 01Find paths to predecessor and successor around target.
- 02Use stacks to produce next lower and next higher values.
- 03Compare absolute distances and consume the closer side.
- 04Repeat until k values are selected.
Reference answer
Then expect these follow-ups
How would you solve it with an inorder deque?
Tests: alternative approach
How do you handle equal-distance ties?
Tests: specification
Free to read · better with Enzo
Practice this out loud with Enzo
Enzo runs it as a mock interview, pushes back with follow-ups, and grades you on the rubric.
Next question