Closest Binary Search Tree Value I & II

时间:2023-03-09 18:55:21
Closest Binary Search Tree Value I & II

Closest Binary Search Tree Value

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

Note: Given target value is a floating point. You are guaranteed to have only one unique value in the BST that is closest to the target.

 public class Solution {
public int closestValue(TreeNode root, double target) {
int closest = root.val;
while(root != null){
// 如果该节点的离目标更近,则更新到目前为止的最近值
closest = Math.abs(closest - target) < Math.abs(root.val - target) ? closest : root.val;
// 二叉搜索
root = target < root.val ? root.left : root.right;
}
return closest;
}
}

Leetcode: 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)?
 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<Double> maxHeap = new PriorityQueue<Double>(k, new Comparator<Double>() {
@Override
public int compare(Double x, Double y) {
return (int) (y - x);
}
}); Set<Integer> set = new HashSet<Integer>();
rec(root, target, k, maxHeap, set);
return new ArrayList<Integer>(set);
} private void rec(TreeNode root, double target, int k, PriorityQueue<Double> maxHeap, Set<Integer> set) {
if (root == null) return; double diff = Math.abs(root.val - target);
if (maxHeap.size() < k) {
maxHeap.offer(diff);
set.add(root.val);
} else if (diff < maxHeap.peek()) {
double x = maxHeap.poll();
if (!set.remove((int) (target + x))) {
set.remove((int) (target - x));
}
maxHeap.offer(diff);
set.add(root.val);
} else {
if (root.val > target) {
rec(root.left, target, k, maxHeap, set);
} else {
rec(root.right, target, k, maxHeap, set);
}
return;
}
rec(root.left, target, k, maxHeap, set);
rec(root.right, target, k, maxHeap, set);
}
}