Trees · Problem 3 of 3

List a tree level by level

Pattern: Binary Tree Level Order Traversal (BFS)

mediumNot solved yet

The problem

Write a function that returns a tree's values level by level: a list of lists, where the first list holds the root's value, the next holds the values one level down (left to right), and so on. An empty tree gives an empty list.

text
1values_by_level([3, 9, 20, None, None, 15, 7])  ->  [[3], [9, 20], [15, 7]]
2values_by_level([1, 2, None, 3])                ->  [[1], [2], [3]]
3values_by_level([])                             ->  []
Example 11 / 3
3920157

[3]

Write values_by_level(root) in Python or valuesByLevel(root) in JavaScript. Examples are written in Python: in JavaScript, None is null and True / False are true / false.

Runs privately in your browser. Nothing is sent to a server.Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Write your function, then run it against 16 tests.

Breakdown

Stuck? Reveal one step at a time, and try again after each one.

  1. Step 2
  2. Step 3
  3. Step 4

Solution

?

Give it a real try first: you learn far more from a wrong attempt than from reading the answer.