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] ]
重点就是用一个变量来记录是从左至右还是从右至左,如果从右至左,reverse一下当前level的节点就可以了。
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> results = new ArrayList<List<Integer>>();
if (root==null) {
return results;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
int currentLevelCount = 1;
int nextLevelCount = 0;
ArrayList<Integer> level = new ArrayList<Integer>();
boolean fromLeftToRight = true;
while (!queue.isEmpty()) {
TreeNode currentNode = queue.poll();
currentLevelCount = currentLevelCount - 1;
//when adding from right to left order, we need to append to the first position
level.add(currentNode.val);
if (currentNode.left!=null) {
queue.add(currentNode.left);
nextLevelCount++;
}
if (currentNode.right!=null) {
queue.add(currentNode.right);
nextLevelCount++;
}
if (currentLevelCount==0) {
if (!fromLeftToRight) {
Collections.reverse(level);
}
currentLevelCount = nextLevelCount;
nextLevelCount = 0;
results.add(new ArrayList<Integer>(level));
level.clear();
fromLeftToRight = !fromLeftToRight;
}
}
return results;
}