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] ]
与上一题类似
不同在于,奇数层 正着存,偶数层,倒着存。
1 class Solution { 2 public List<List<Integer>> zigzagLevelOrder(TreeNode root) { 3 List<List<Integer>> res = new ArrayList<List<Integer>>(); 4 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 5 if(root==null) return res; 6 int flag =1; 7 queue.add(root); 8 while (!queue.isEmpty()) { 9 int levlnum = queue.size(); 10 List<Integer> res_temp = new ArrayList<Integer>(); 11 for (int i = 0;i<levlnum ;i++ ){ //把每层的左右节点都保存到queue里 12 //并讲当层的值从queue里弹出,加到res_temp 中 13 if(queue.peek().left!=null) queue.add(queue.peek().left); 14 if(queue.peek().right!=null) queue.add(queue.peek().right); 15 if(flag==1) 16 res_temp.add(queue.poll().val); 17 else 18 res_temp.add(0,queue.poll().val); 19 } 20 res.add(res_temp); 21 flag = 1-flag; 22 } 23 return res; 24 }