题解:层次遍历的基础上加个计数器,偶数层得到的结果反转一下
/**
* 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) {
if(root == null) return new ArrayList<>();
List<List<Integer>> res = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
int cnt = 0;
q.add(root);
while(true){
List<Integer> list = new ArrayList<>();//定义到外面之后用clear会出错
int size = q.size();
cnt++;
for(int i=0;i<size;i++){
TreeNode t = q.poll();
list.add(t.val);
if(t.left != null){
q.add(t.left);
}
if(t.right != null){
q.add(t.right);
}
}
if(cnt % 2 == 0){
Collections.reverse(list);
}
res.add(list);
if(q.size() == 0) break;
}
return res;
}
}