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],
3
/ \
9 20
/ \
15 7
return its zigzag level order traversal as:
[
[3],
[20,9],
[15,7]
]
思路
- 和Level Order Traverse一致,但不同的地方在于,隔行的结果需要翻转。比如1,3,5行是从左到右,2,4,6行就是从右到左。
- 用一个外部变量Depth记录当前结果是数的第几层,当depth为奇数层时,不做任何处理直接向结果中加入layer; 如果为偶数时,则Collections.reverse(layer),再将其加入到结果中即可。
/**
* 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>> result = new ArrayList<>();
if (root == null) return result;
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
int depth = 0;
while(!queue.isEmpty()) {
int size = queue.size();
depth++;
List<Integer> layer = new ArrayList<Integer>();
for (int i = 0; i < size; i++) {
TreeNode curNode = queue.poll();
if (curNode.left != null) {
queue.add(curNode.left);
}
if (curNode.right != null) {
queue.add(curNode.right);
}
layer.add(curNode.val);
}
if (depth % 2 == 0) {
Collections.reverse(layer);
}
result.add(layer);
}
return result;
}
}