Closest Binary Search Tree Value II

Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.

Note:

Given target value is a floating point. You may assume k is always valid, that is: k ≤ total nodes. You are guaranteed to have only one unique set of k values in the BST that are closest to the target.

Follow up: Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)?

Solution

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {

    public List<Integer> closestKValues(TreeNode root, double target, int k) {
        PriorityQueue<Result> queue = new PriorityQueue<>(k, (a, b) -> -Double.compare(a.diff, b.diff));
        traverse(root, queue, target, k);

        List<Integer> result = new ArrayList<>();
        while (!queue.isEmpty()) {
            result.add(queue.poll().value);
        }
        return result;
    }

    private void traverse(TreeNode node, PriorityQueue<Result> queue, double target, int k) {
        if (node == null) return;

        double diff = Math.abs(node.val - target);

        queue.add(new Result(node.val, diff));
        if (queue.size() > k) {
            queue.poll();
        }

        traverse(node.left, queue, target, k);
        traverse(node.right, queue, target, k);
    }

    private class Result {
        private int value;
        private double diff;

        public Result(int value, double diff) {
            this.value = value;
            this.diff = diff;
        }
    }

}

results matching ""

    No results matching ""