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).
For example:
Given binary tree [3,9,20,null,null,15,7],
return its zigzag level order traversal as:
Solution
BFS
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> levelsList = new LinkedList();
if (root == null) return levelsList;
Queue<TreeNode> queue = new LinkedList();
queue.add(root);
boolean isReverse = false;
while (!queue.isEmpty()) {
int nodesCount = queue.size();
List<Integer> levelList = new LinkedList();
for (int i = 0; i < nodesCount; ++i) {
TreeNode p = queue.poll();
if (p.left != null) queue.add(p.left); // filter null nodes
if (p.right != null) queue.add(p.right);
if (!isReverse) {
levelList.add(p.val);
} else {
levelList.add(0, p.val);
}
}
levelsList.add(levelList);
isReverse = !isReverse; // flip the order
}
return levelsList;
}
}