TREE-P1

Level by level

Practice 1 of 6Trees and BSTs9 tests

The problem

Return the values of a binary tree level by level: a list of lists, one per level, from the root down. Inside a level, list the values from left to right.

tree [3, 9, 20, None, None, 15, 7]  ->  [[3], [9, 20], [15, 7]]
tree [1, 2, 3, None, 4, None, 5]    ->  [[1], [2, 3], [4, 5]]
empty tree                          ->  []

The tests write a tree as a level-order list: the values level by level, left to right, with None where a child is missing. So [3, 9, 20, None, None, 15, 7] is 3 with children 9 and 20, where 20 has children 15 and 7. An empty tree is None.

Limits

  • Up to 100,000 nodes.
  • The tree can be 5,000 levels deep, so a recursive solution will stop with RecursionError. Use a queue.

Builds on TREE-1 Vocabulary and TREE-2 Traversals.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

9 tests, not run yet
Test results
#TestResultReads · time
1Small treeNot run
2Empty treeNot run
3One nodeNot run
4The lessons' treeNot run
5GapsNot run
6Leaning leftNot run
7Perfect tree of 15Not run
85,000 levelsNot run
9100,000 nodesNot run