和102是一样的
用Collections.reverse(list)来翻转list
1 public List
> zigzagLevelOrder(TreeNode root) { 2 List
> res = new ArrayList
>(); 3 if(root == null) { 4 return res; 5 } 6 LinkedList queue = new LinkedList (); 7 queue.offer(root); 8 int lastLevelCnt = 1; 9 int curLevelCnt = 0;10 List curLevel = new ArrayList ();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 ();33 }34 }35 return res;36 }