二刷272. Closest Binary Search Tre

2018-01-31  本文已影响0人  greatseniorsde

第二遍写出了一点小bug.

/**
 * 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;        
    }
}
上一篇 下一篇

猜你喜欢

热点阅读