Leetcode - Closest Binary Search Tree Value II

12 篇文章 0 订阅
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)?

[分析]
参考[url]https://leetcode.com/discuss/55240/ac-clean-java-solution-using-two-stacks[/url]
中序遍历结果是将树中元素从小到大排列,逆式的中序遍历即先遍历右子树再访问根节点最后遍历左子树会得到树中元素从大到小排列的结果,因此可通过中序遍历获取最接近target节点的perdecessors,通过逆中序遍历获取最接近target节点的successors,然后merge perdecessors 和 successors 获取最接近target节点的 k个节点值。
注意到在中序遍历时遇到比target 大的节点即停止,因为由BST的性质可知后面的元素均会比target 大,即所有target的predecessors均已找到,同理逆中序遍历时遇到不大于 target的节点即可停止递归。


/**
* Definition for a binary tree node.
* public 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) {
List<Integer> result = new ArrayList<Integer>();
LinkedList<Integer> stackPre = new LinkedList<Integer>();
LinkedList<Integer> stackSucc = new LinkedList<Integer>();
inorder(root, target, false, stackPre);
inorder(root, target, true, stackSucc);
while (k-- > 0) {
if (stackPre.isEmpty()) {
result.add(stackSucc.pop());
} else if (stackSucc.isEmpty()) {
result.add(stackPre.pop());
} else if (Math.abs(stackPre.peek() - target) < Math.abs(stackSucc.peek() - target)) {
result.add(stackPre.pop());
} else {
result.add(stackSucc.pop());
}
}
return result;
}
public void inorder(TreeNode root, double target, boolean reverse, LinkedList<Integer> stack) {
if (root == null) return;
inorder(reverse ? root.right : root.left, target, reverse, stack);
if ((reverse && root.val <= target) || (!reverse && root.val > target))
return;
stack.push(root.val);
inorder(reverse ? root.left : root.right, target, reverse, stack);
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值