import java.util.concurrent.LinkedBlockingQueue;


/*
 * 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) {
        // write code here
        if(root == null){
            return new ArrayList<>(0);
        }
        ArrayList<ArrayList<Integer>> result = new ArrayList<>();
        
        Queue<TreeNode> queue = new LinkedBlockingQueue<>();
        queue.add(root);
        //队列 先进先出
        while(!queue.isEmpty()){
            int size = queue.size();
            ArrayList<Integer> lineResult = new ArrayList<>();
            while(size > 0){
                TreeNode node = queue.poll();
                if(node.left != null){
                    queue.add(node.left);
                }
                if(node.right != null){
                    queue.add(node.right);
                }
                lineResult.add(node.val);
                size --;
            }
            if(!lineResult.isEmpty()){
                result.add(lineResult);
            }
            
        }
        
        return result;
    }
}