Practice: Binary Tree Level Order Traversal
Problem: https://leetcode.com/problems/binary-tree-level-order-traversal/
Recognition reminder: the output is grouped by level (“the values at depth 0, then depth 1, …”). “Level by level” is the BFS cue. DFS can be made to work, but BFS with a queue is the natural fit, and the skill is processing exactly one full level per outer step.
Before you start (the five-beat rhythm)
- Your Pattern Card for this week is already written.
- Name the pattern aloud and write your approach as a plain-English comment before any code.
- Struggle floor: 25 minutes unaided. No hints, no AI, no Discuss tab.
- If stuck past the floor, ask the tutor for a hint. Six rungs, one per ask.
- Debrief in your commit message before moving to the next problem.
Your target
Fill these in yourself before you look at anyone else’s solution:
Target time complexity: ____
Target space complexity: ____
You visit every node once, so think about what time that forces. For space, the question is how wide the tree can get: the queue holds at most one level at a time, so what is the largest a single level can be? Name what dominates.
The shape of the input and the output
You implement a function level_order(root) -> list[list[int]]. The argument root is a TreeNode (with val, left, right) or None for an empty tree. You return a list of levels, each level a list of node values left-to-right: for the tree [3, 9, 20, null, null, 15, 7] the answer is [[3], [9, 20], [15, 7]]. The empty tree returns [].
The trick that the test cannot teach you: when you pull from the queue, you must process exactly the nodes that are currently in it (one whole level) before touching any of their children, or your levels will smear together. Capture the queue’s length at the top of each outer step, and loop that many times.
Where your code goes
Write your solution as a function level_order(root) in a file named solution.py in your own work repo (see getting-started.md), not in the course repo. Define your own TreeNode class (the same three-attribute shape the test uses) so your function can build and read nodes. This folder ships only the problem spec and a provided-example test (tests/test_provided.py) so you can check the given cases locally before you submit to LeetCode’s judge. The test builds real trees for you from level-order lists; read its build_tree helper so you know the node shape it expects. The judge is the oracle; the tutor will not confirm your answer by reading it.
Debrief (paste into your commit message)
1. What pattern did this turn out to be?
2. What was the trigger phrase or input shape that should have made me reach for it?
3. What was the time and space complexity, and what would dominate at scale?
4. What edge case would have broken my first attempt?
5. What would I do differently in three days when I see this cold?