题目:
分析:
深度遍历这棵树,然后判断当前层数,若为偶数层,该list反转。
代码:
/**
* 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>> levelOrder(TreeNode root) {
List<List<Integer>> list =new ArrayList();
Queue<TreeNode> q=new LinkedList();
int i=1;
q.offer(root);
q.offer(null);
while(q.peek()!=null){
List<Integer> l=new ArrayList();
list.add(l);
while(q.peek()!=null){
TreeNode t=q.poll();
if(t.left!=null){
q.offer(t.left);
}
if(t.right!=null){
q.offer(t.right);
}
l.add(t.val);
}
q.remove();
q.offer(null);
if(i%2==0){
Collections.reverse(l);
}
i++;
}
return list;
}
}