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<>();

        if (root == null) {
            return result;
        }

        //利用队列先进先出 保证每个层级入队出队的顺序 再结合队列的长度做同一层级节点的个数统计判断
        LinkedList<TreeNode> queue = new LinkedList<>();
        queue.offer(root);

        //同一层级节点保存的List
        ArrayList<Integer> listForTreeLevel = null;

        while (!queue.isEmpty()) {

             //先存取之前队列中的长度 这样就保证了之前的长度代表二叉树 同一层中节点的个数
            int queueSize = queue.size();

            listForTreeLevel = new ArrayList();

            while (queueSize-- > 0) {

                TreeNode tree = queue.poll();

                listForTreeLevel.add(tree.val);

                if (tree.left != null) {
                    queue.offer(tree.left);
                }

                if (tree.right != null) {
                    queue.offer(tree.right);
                }
            }

            result.add(listForTreeLevel);

        }

        return result;

    }
}