题目
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,#,#,15,7}
,
3 / \ 9 20 / \ 15 7
return its zigzag level order traversal as:
[ [3], [20,9], [15,7] ]
广度遍历,每层翻转
1 Collections.reverse()这个函数真好!
2 广度遍历是基础的基础,要记得多练习。
public class Solution {
public ArrayList<ArrayList<Integer>> zigzagLevelOrder(TreeNode root) {
ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>();
if(root==null){
return ans;
}
ArrayList<Integer> temp = new ArrayList<Integer>();
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.add(root);
boolean reverse = false;
int num = 0;
int count =1;
while(!queue.isEmpty()){
TreeNode cur = queue.remove();
temp.add(cur.val);
count--;
if(cur.left!=null){
queue.add(cur.left);
num++;
}
if(cur.right!=null){
queue.add(cur.right);
num++;
}
if(count==0){
count=num;
num=0;
if(reverse){
Collections.reverse(temp);
reverse=false;
}
else{
reverse=true;
}
ans.add(new ArrayList<Integer>(temp));
temp.clear();
}
}
return ans;
}
}