270. 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.

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

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)?
 1 class TreeNode {
 2     int val;
 3     TreeNode left;
 4     TreeNode right;
 5 
 6     TreeNode(int x) {
 7         val = x;
 8     }
 9 }
10 
11 public class Solution {
12 
13     public List<Integer> closestKValues(TreeNode root, double target, int k) {
14         PriorityQueue<Double> maxHeap = new PriorityQueue<Double>(k, new Comparator<Double>() {
15             @Override
16             public int compare(Double x, Double y) {
17                 return (int) (y - x);
18             }
19         });
20 
21         Set<Integer> set = new HashSet<Integer>();
22         rec(root, target, k, maxHeap, set);
23         return new ArrayList<Integer>(set);
24     }
25 
26     private void rec(TreeNode root, double target, int k, PriorityQueue<Double> maxHeap, Set<Integer> set) {
27         if (root == null) return;
28         
29         double diff = Math.abs(root.val - target);
30         if (maxHeap.size() < k) {
31             maxHeap.offer(diff);
32             set.add(root.val);
33         } else if (diff < maxHeap.peek()) {
34             double x = maxHeap.poll();
35             if (!set.remove((int) (target + x))) {
36                 set.remove((int) (target - x));
37             }
38             maxHeap.offer(diff);
39             set.add(root.val);
40         } else {
41             if (root.val > target) {
42                 rec(root.left, target, k, maxHeap, set);
43             } else {
44                 rec(root.right, target, k, maxHeap, set);
45             }
46             return;
47         }
48         rec(root.left, target, k, maxHeap, set);
49         rec(root.right, target, k, maxHeap, set);
50     }
51 }

 

posted @ 2016-10-18 11:24  北叶青藤  阅读(226)  评论(0编辑  收藏  举报