Use one queue + size variable
1 public class Solution { 2 public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) { 3 ArrayList result = new ArrayList(); 4 if (root == null) 5 return result; 6 Queue<TreeNode> queue = new LinkedList<TreeNode>(); 7 queue.offer(root); 8 9 while (!queue.isEmpty()) { 10 int size = queue.size(); 11 ArrayList<Integer> level = new ArrayList<Integer>(); 12 for (int i = 0; i < size; i++) { 13 TreeNode head = queue.poll(); 14 level.add(head.val); 15 if (head.left != null) 16 queue.offer(head.left); 17 if (head.right != null) 18 queue.offer(head.right); 19 } 20 result.add(level); 21 } 22 return result; 23 } 24 }