`

Leetcode - Closest Binary Search Tree Value II

 
阅读更多
[分析]
思路1:遍历所有节点找到和 target最接近的 k 个元素,能否有个数据结构在遍历过程中维护已遍历元素离target最近的呢?PriorityQueue具备这种能力。我们需要个最小堆,堆元素需要保存两个信息,一个是树节点元素值,一个是这个元素和target的差的绝对值。但PriorityQueue是没有“堆底”概念的,当堆的size 增长到 k 后,如何删除堆中最大元素呢? 为实现删除最小堆中最大值的操作,可以再维护一个最大堆,两个堆同步更新,需要从堆中删除元素时一定时删除最大堆的堆顶元素。
实现注意点:
1)想清楚堆节点元素保存什么信息
2)新定义的Pair类要么实现了Comparable接口,要么在创建堆时传入比较器,否则运行时抛异常(PriorityQueue在JAVA文档中是这么声明的:A priority queue relying on natural ordering also does not permit insertion of non-comparable objects (doing so may result in ClassCastException).)。
3)minHeap 靠maxHeap来删除元素,因此往两个堆中添加元素时必须时同一个对象。
思路2:参考https://leetcode.com/discuss/55240/ac-clean-java-solution-using-two-stacks。 作者非常巧妙的利用了inorder遍历的特性,inorder遍历可得到某个元素的sorted predecessors, 逆inorder则可得到sorted successors.强悍!

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    Comparator<Pair> ascendComparator = new Comparator<Pair>() {
        public int compare(Pair a, Pair b) {
            return (int)(a.diff - b.diff);
        }
    };
    Comparator<Pair> descendComparator = new Comparator<Pair>() {
        public int compare(Pair a, Pair b) {
            return (int)(b.diff - a.diff);
        }
    };
    public List<Integer> closestKValues(TreeNode root, double target, int k) {
        List<Integer> result = new ArrayList<Integer>();
        if (root == null) return result;
        
        PriorityQueue<Pair> minHeap = new PriorityQueue<Pair>(k, ascendComparator);
        PriorityQueue<Pair> maxHeap = new PriorityQueue<Pair>(k, descendComparator);
        helper(root, target, k, minHeap, maxHeap);
        
        Iterator<Pair> iter = minHeap.iterator();
        while (iter.hasNext()) {
            result.add(iter.next().value);
        }
        return result;
    }
    public void helper(TreeNode root, double target, int k, PriorityQueue<Pair> minHeap, PriorityQueue<Pair> maxHeap) {
        if (root != null) {
            double currDiff = Math.abs(root.val - target);
            if (minHeap.size() < k || currDiff < maxHeap.peek().diff) {
                if (minHeap.size() == k) {
                    minHeap.remove(maxHeap.poll());
                }
                Pair pair = new Pair(currDiff, root.val);
                minHeap.offer(pair);
                maxHeap.offer(pair);
            }
            helper(root.left, target, k, minHeap, maxHeap);
            helper(root.right, target, k, minHeap, maxHeap);
        }
    }
    
    class Pair{
        double diff;
        int value;
        public Pair(double diff, int value) {
            this.diff = diff;
            this.value = value;
        }
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics