- Binary Tree Zigzag Level Order Traversal这道题每一层加入节点val的时候,如果是用arraylist, 需要O(n) 用LinkedList只需要O(1)就可以插入头部或者尾部。但初始化LinkedList的时候不能用List interface, 要直接用LinkedList,不然找不到addFirst,removeFirst这些方法
/**
* 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);
int count = 0;
while (!queue.isEmpty()){
LinkedList<Integer> level = new LinkedList<>();
int size = queue.size();
for (int i = 0; i < size; i++){
TreeNode curt = queue.poll();
if (count % 2 == 0){
level.add(curt.val);
} else {
level.addFirst(curt.val);
}
if (curt.left != null){
queue.offer(curt.left);
}
if (curt.right != null){
queue.offer(curt.right);
}
}
count++;
res.add(level);
}
return res;
}
}