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] ]
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
//Definition for a binary tree node.
public class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
class Solution {
public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
if(root == null) return new ArrayList<List<Integer>>();
int count = 1;
List<List<Integer>> list = new ArrayList<List<Integer>>();
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.add(root);
while(q.size()>0){
int size = q.size();
List<Integer> inlist = new ArrayList<Integer>();
for(int i=0; i<size; i++){
TreeNode front = q.poll();
inlist.add(front.val);
if(front.left != null){
q.add(front.left);
}
if(front.right != null){
q.add(front.right);
}
}
if(count%2 == 0){
reverse(inlist);
}
list.add(inlist);
count++;
}
return list;
}
public static void reverse(List<Integer> list) {
int size = list.size();
for(int i = 0; i<size/2; i++){
int front = list.get(i);
int tail = list.get(size-1-i);
list.set(i, tail);
list.set(size-1-i, front);
}
}
}
和102题的思路一样,就是在将inlist放入list之前加了一步判断,如果是偶数层将链表进行一次反转,然后加入整个链表中。