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]
]
题目
思路
1. use Queue to help BFS
2. once scan current level, make a U-turn, then scan next level
代码
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
int level = 0;
// lever order traversal
while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
TreeNode node = queue.remove();
if (node != null) {
list.add(node.val);8
queue.add(node.left);
queue.add(node.right);
}
}
if (!list.isEmpty()) {
// make a U-turn
if (level % 2 == 1) {
Collections.reverse(list);
}
result.add(list);
}
level++;
}
return result;
}
}