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; } * } */publicclassSolution {publicList<Integer> closestKValues(TreeNode root,double target,int k) {PriorityQueue<Result> queue =newPriorityQueue<>(k, (a, b) ->-Double.compare(a.diff,b.diff));traverse(root, queue, target, k);List<Integer> result =newArrayList<>();while (!queue.isEmpty()) {result.add(queue.poll().value); }return result; }privatevoidtraverse(TreeNode node,PriorityQueue<Result> queue,double target,int k) {if (node ==null) return;double diff =Math.abs(node.val- target);queue.add(newResult(node.val, diff));if (queue.size() > k) {queue.poll(); }traverse(node.left, queue, target, k);traverse(node.right, queue, target, k); }privateclassResult {privateint value;privatedouble diff;publicResult(int value,double diff) {this.value= value;this.diff= diff; } }}