# Binary Tree Zigzag Level Order Traversal

## Question

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
Given binary tree {3,9,20,#,#,15,7},

3
/ \
9  20
/  \
15   7

return its zigzag level order traversal as:

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

## 题解1 - 队列

### Java

/**
* 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: The root of binary tree.
* @return: A list of lists of integer include
*          the zigzag level order traversal of its nodes' values
*/
public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
if (root == null) return result;

boolean odd = true;
q.offer(root);
while (!q.isEmpty()) {
// level traversal
int qLen = q.size();
ArrayList<Integer> level = new ArrayList<Integer>();
for (int i = 0; i < qLen; i++) {
TreeNode node = q.poll();
if (node.left != null) q.offer(node.left);
if (node.right != null) q.offer(node.right);
}
// add level order reverse for even
if (odd) {
} else {
Collections.reverse(level);
}
// flip odd and even
odd = !odd;
}

return result;
}
}