Accepted Heap Solution


  • 0
    R
    public void closestKValuesUtil(TreeNode root, double target, int k,Queue<Integer> queue){
            if(root == null){
                return ;
            }
    
            closestKValuesUtil(root.left,target,k,queue);
            if(queue.size() < k){
                queue.offer(root.val);
            }
            else{
                if(Math.abs(queue.peek() - target) > Math.abs(root.val-target)){
                    queue.poll();
                    queue.add(root.val);
                }
            }
            closestKValuesUtil(root.right,target,k,queue);
        }
    
        public List<Integer> closestKValues(TreeNode root, double target, int k) {
            final double value = target;
            Queue<Integer> myqueue = new PriorityQueue<Integer>(new Comparator<Integer>() {
                public int compare(Integer o1, Integer o2) {
                    if(o1==o2){
                        return 0;
                    }
                    if(Math.abs(o1-value)< Math.abs(o2-value)){
                        return 1;
                    }
                    else{
                        return -1;
                    }
                }
            });
            closestKValuesUtil(root,target,k,myqueue);
            return  new ArrayList<Integer>(myqueue);
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.