第二遍写出了一点小bug.
- 一是要注意一定要写LinkedList<Integer>,不要写List<>,因为LinkedList有些特殊的接口只有它有。
- 在res.size() == k之后,如果发现当前点到target的距离大于res里首个元素到target的距离,就要直接退出循环(break), 因为后面的点离target的距离会越来越大。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> closestKValues(TreeNode root, double target, int k) {
LinkedList<Integer> res = new LinkedList<>();
Stack<TreeNode> stack = new Stack<>();
TreeNode curt = root;
while (curt != null){
stack.push(curt);
curt = curt.left;
}
while (!stack.isEmpty()){
curt = stack.pop();
if (res.size() >= k){
if (Math.abs(curt.val - target) - Math.abs(res.getFirst() - target) < 0){
res.removeFirst();
res.add(curt.val);
} else {
break;
}
} else {
res.add(curt.val);
}
if (curt.right != null){
curt = curt.right;
while (curt != null){
stack.push(curt);
curt = curt.left;
}
}
}
return res;
}
}
网友评论