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 { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param pRoot TreeNode类 * @return int整型ArrayList<ArrayList<>> */ public ArrayList<ArrayList<Integer>> Print (TreeNode pRoot) { // write code here // 解题思路:层序遍历时间复杂度要求O(n),可以采用队列来实现 if (pRoot == null) { return new ArrayList(); } Queue<TreeNode> queue = new LinkedList<>(); queue.offer(pRoot); ArrayList<ArrayList<Integer>> arrayList = new ArrayList<>(); boolean resever = true; while (!queue.isEmpty()) { ArrayList<Integer> list = new ArrayList<>(); int l = queue.size(); resever = !resever; for (int i = 0; i < l; i++) { TreeNode node = queue.poll(); list.add(node.val); if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } } if (resever) { Collections.reverse(list); } arrayList.add(list); } return arrayList; } }