import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * } */ public class Solution { /** * * @param root TreeNode类 * @return int整型ArrayList<ArrayList<>> */ public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); if (root == null) { return result; } LinkedList<TreeNode> queue = new LinkedList<>(); queue.add(root); while (!queue.isEmpty()) { ArrayList<Integer> list = new ArrayList<Integer>(); int queueSize = queue.size(); //不能写成这样 不然随着第一个节点入队列后,有左右孩子的话 那么queue.size()还会被更新为有,所以要把queue.size()提出去作为一个变量 // for (int i = 0; i < queue.size(); i++) { for (int i = 0; i < queueSize; i++) { TreeNode node = queue.poll(); list.add(node.val); if (node.left != null) { queue.add(node.left); } if (node.right != null) { queue.add(node.right); } } result.add(list); } return result; } }