103. Binary Tree Zigzag Level Order Traversal

题目描述

103. Binary Tree Zigzag Level Order Traversal

题目链接

https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/

方法思路

类似于层序遍历,使用了队列的数据结构,但是不清楚为什么LinkedList的方法addFirst() 用不了。只能用ArrayList的 add(int index, E e) 方法来实现遍历。

class Solution {
    //Runtime: 0 ms, faster than 100.00% 
    //Memory Usage: 37.1 MB, less than 62.52%
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> ans = new LinkedList<>();
        if(root == null) return ans;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int count = 0;
        while(!queue.isEmpty()){
            int size = queue.size();
            List<Integer> list = new ArrayList<>();
            while(size-- > 0){
                TreeNode node = queue.poll();
                if(count % 2 == 0) 
                    list.add(node.val);
                else 
                    list.add(0, node.val);
                if(node.left != null) queue.offer(node.left);
                if(node.right != null) queue.offer(node.right);
            }
            count++;
            ans.add(list);
        }
        return ans;
    }
}