103. Binary Tree Zigzag Level Order Traversal
和102是一样的
用Collections.reverse(list)来翻转list
1 public List<List<Integer>> zigzagLevelOrder(TreeNode root) { 2 List<List<Integer>> res = new ArrayList<List<Integer>>(); 3 if(root == null) { 4 return res; 5 } 6 LinkedList<TreeNode> queue = new LinkedList<TreeNode>(); 7 queue.offer(root); 8 int lastLevelCnt = 1; 9 int curLevelCnt = 0; 10 List<Integer> curLevel = new ArrayList<Integer>(); 11 boolean reverse = false; 12 while(!queue.isEmpty()) { 13 TreeNode cur = queue.poll(); 14 curLevel.add(cur.val); 15 lastLevelCnt--; 16 if(cur.left != null) { 17 queue.offer(cur.left); 18 curLevelCnt++; 19 } 20 if(cur.right != null) { 21 queue.offer(cur.right); 22 curLevelCnt++; 23 } 24 if(lastLevelCnt == 0) { 25 if(reverse) { 26 Collections.reverse(curLevel); 27 } 28 reverse = !reverse; 29 res.add(curLevel); 30 lastLevelCnt = curLevelCnt; 31 curLevelCnt = 0; 32 curLevel = new ArrayList<Integer>(); 33 } 34 } 35 return res; 36 }