Leetcode - Closest Binary Search Tree Value II

12 篇文章 0 订阅
1 篇文章 0 订阅
[分析]
思路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:参考[url]https://leetcode.com/discuss/55240/ac-clean-java-solution-using-two-stacks[/url]。 作者非常巧妙的利用了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;
}
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值