
思路:看到这道题的思路是,层序遍历 然后如何达到题目中说的锯齿的要求就是,用一个数字的与2除模来确定当前的行数是单数行还是偶数行,如果是单数行则先存根节点的右子节点,然后再存根节点的左子节点。即偶数行是倒序的。
首先补充知识:反转动态list数组的方法是 Collections.reverse();

记住!!!!题目没有说为非空二叉树一定要提前判断是否是空!!!!
一开始的错误代码和调试
修改过后的代码:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
Deque<TreeNode> que = new LinkedList<>();
List<List<Integer>> res = new ArrayList<>();
que.offer(root);
int count = 0;
if( root == null){
return res;
}
while(!que.isEmpty()){
count++;
int size = que.size();
List<Integer> list = new ArrayList<>();
while(size > 0){
TreeNode cur = que.poll();
list.add(cur.val);
size--;
if(size == 0){
if(count % 2 == 0){
Collections.reverse(list);
}
res.add(list);
}
if(cur.left != null){
que.offer(cur.left);
}
if(cur.right != null){
que.offer(cur.right);
}
}
}
return res;
}
}