Binary Tree Zigzag Level Order Traversal
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,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
public class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null) {
return result;
}
Stack<TreeNode> curList = new Stack<TreeNode>();
curList.add(root);
int level = 0;
while (!curList.isEmpty()) {
List<Integer> newList = new ArrayList<Integer>();
Stack<TreeNode> children = new Stack<TreeNode>();
while(!curList.isEmpty()) {
TreeNode curNode = curList.pop();
newList.add(curNode.val);
if (level%2==0) { // left to right
if (curNode.left != null) {
children.push(curNode.left);
}
if (curNode.right != null) {
children.push(curNode.right);
}
} else { // right to left
if (curNode.right != null) {
children.push(curNode.right);
}
if (curNode.left != null) {
children.push(curNode.left);
}
}
}
result.add(newList);
level++;
curList = children;
}
return result;
}
}