↻one more pass.
Trees · Medium

Binary Tree Level Order Traversal: the idea to remember.

Return tree values grouped by depth, from the root downward.

Solve on LeetCode ↗

The core insight

Use BFS and consume exactly the queue size captured at the start of each level.

Why it works

The queue initially contains all nodes at the current depth. Their children are appended for the next depth without entering the current group.

The mistake to avoid

Do not use a changing queue.size() as the loop bound while adding children.

Time: O(n)Space: O(w), plus output

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

List<List<Integer>> levelOrder(TreeNode root) {
    List<List<Integer>> out = new ArrayList<>();
    if (root == null) return out;
    Deque<TreeNode> queue = new ArrayDeque<>(); queue.add(root);
    while (!queue.isEmpty()) {
        int width = queue.size(); List<Integer> level = new ArrayList<>();
        for (int i = 0; i < width; i++) {
            TreeNode node = queue.remove(); level.add(node.val);
            if (node.left != null) queue.add(node.left);
            if (node.right != null) queue.add(node.right);
        }
        out.add(level);
    }
    return out;
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.