71 · Binary Tree Zigzag Level Order Traversal - LintCode

# Description

Given a binary tree, return the zigzag level order traversal of its nodes' values. (ie, from left to right, then right to left for the next level and alternate between).

# Example

Example 1:

Input:

tree = {1,2,3}

Output:

[[1],[3,2]]

Explanation:

    1
   / \
  2   3

it will be serialized {1,2,3}
Example 2:

Input:

tree = {3,9,20,#,#,15,7}

Output:

[[3],[20,9],[15,7]]

Explanation:

    3
   / \
  9  20
    /  \
   15   7

it will be serialized

# Solution

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param root: A Tree
     * @return: A list of lists of integer include the zigzag level order traversal of its nodes' values.
     */
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List list = new ArrayList<>();
        if (root == null) return list;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int countLevel = 1;
        while (!queue.isEmpty()) {
            int size = queue.size();
            ArrayList<Integer> level = new ArrayList<>();
            for (int i = 0; i < size; i++){
                TreeNode node = queue.poll();
                level.add(node.val);
                if (node.left != null) queue.offer(node.left);
                if (node.right != null) queue.offer(node.right);
            }
            if (countLevel % 2 == 0) {
                Collections.reverse(level);
            }
            countLevel++;
            list.add(level);
        }
        return list;
    }
}