JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

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);
    }
}