Medium
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按照Level Order Traversal来遍历。然后选择奇数层,翻转一下对应的ArrayList<Integer> 就可以了。翻转的写法我是搜到的,list.add(i,e)这个写法是把Element e insert到index = i的位置,很少用但很方便的一个method.
/**
* 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>> res = new ArrayList<>();
if (root == null){
return res;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()){
int size = queue.size();
List<Integer> level = new ArrayList<>();
for (int i = 0; i < size; i++){
TreeNode curt = queue.poll();
level.add(curt.val);
if (curt.left != null){
queue.offer(curt.left);
}
if (curt.right != null){
queue.offer(curt.right);
}
}
res.add(level);
}
for (int i = 0; i < res.size(); i++){
if (i % 2 != 0){
List<Integer> list = res.get(i);
for (int j = 0, k = list.size() - 1; j < k; j++){
list.add(j, list.remove(k));
}
}
}
return res;
}
}