import java.util.*; /* public class TreeNode { int val = 0; TreeNode left = null; TreeNode right = null; public TreeNode(int val) { this.val = val; } } */ public class Solution { public ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) { ArrayList<ArrayList<Integer>> res = new ArrayList<>(); if(pRoot == null) return res; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(pRoot); int level = 1; while(!queue.isEmpty()){ ArrayList<Integer> list = new ArrayList<Integer>(); int levelLen = queue.size(); for (int i = 0; i < levelLen; i++) { TreeNode node = queue.poll(); if((level % 2) != 0){ // 奇数层 正序 list.add(node.val) ; }else{ // 偶数层 逆序 list.add(0,node.val); } if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } } level++; res.add(new ArrayList<>(list)); } return res; } }