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]
]
BFS遍历,维护一个order变量
order = 0 时,将node节点放入level 后面;
order = 1 时,将node节点放在level前面。
所以,level适合使用LinkedList,方便头部插入。
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<>();
queue.add(root);
int order = 0;
while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> level = new LinkedList<>();
for (int i = 0; i < size; i++) {
TreeNode node = queue.poll();
if (order == 0) {
level.add(node.val);
} else {
level.add(0, node.val);
}
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
order = 1 - order;
result.add(level);
}
return result;
}
}