剑指 Offer 32 - III. 从上到下打印二叉树 III

剑指 Offer 32 - III. 从上到下打印二叉树 III

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> res = new ArrayList<>();
        if(root == null) return res;
        Deque<TreeNode> queue = new ArrayDeque<>();
        queue.offer(root);

        while(!queue.isEmpty()){
            int size = queue.size();
            Deque<Integer> tmp = new ArrayDeque<>();
            for(int i = 0; i < size; i++){
                TreeNode cur = queue.poll();
                if(res.size() % 2 == 1) tmp.offerFirst(cur.val);
                else tmp.offerLast(cur.val);
                if(cur.left != null) queue.offer(cur.left);
                if(cur.right != null) queue.offer(cur.right);
            }
            res.add(new ArrayList<>(tmp));
        }

        return res;
    }
}

你可能感兴趣的:(#,剑指offer,算法)