ID | Title | Difficulty | |
---|---|---|---|
Loading... |
272. Closest Binary Search Tree Value II
Hard
LeetCode
Two Pointers, Stack, Tree, Depth-First Search, Binary Search Tree, Heap (Priority Queue), Binary Tree
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.
Example 1:
Input: root = [4,2,5,1,3], target = 3.714286, k = 2
Output: [4,3]
Example 2:
Input: root = [1], target = 0.000000, k = 1
Output: [1]
Code
class Solution {
public List<Integer> closestKValues(TreeNode root, double target, int k) {
LinkedList<Integer> res = new LinkedList<>();
helper(res, root, target, k);
return res;
}
private void helper(LinkedList<Integer> res, TreeNode root, double target, int k){
if(root == null) return;
helper(res, root.left, target, k);
if(res.size() == k){
if(Math.abs(target - root.val) < Math.abs(target - res.peekFirst())){
res.removeFirst();
} else {
return;
}
}
res.add(root.val);
helper(res, root.right, target, k);
}
}
按 <- 键看上一题!
271. Encode and Decode Strings
按 -> 键看下一题!
273. Integer to English Words