二刷272. Closest Binary Search Tree Value II

第二遍写出了一点小bug.

  • 一是要注意一定要写LinkedList,不要写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 closestKValues(TreeNode root, double target, int k) {
        LinkedList res = new LinkedList<>();
        Stack 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;        
    }
}

你可能感兴趣的:(二刷272. Closest Binary Search Tree Value II)