Editor

Level Order Traversal

#70 · Trees · Intermediate · 65 XP · about 10 min

Write levels(root) that returns the values of a binary tree level by level: a list with one inner list per level, starting at the root, where each inner list goes from left to right. An empty tree gives [].

Each node is a Node with a value val and two children, left and right, which are None when missing. The provided build makes a tree from a list of values in level order, where None marks a missing child.

Examples

    4
   / \
  1   7
     / \
    5   9
levels(build([4, 1, 7, None, None, 5, 9]))  # returns [[4], [1, 7], [5, 9]]
levels(build([1, 2, 3, 4, None, None, 5]))  # returns [[1], [2, 3], [4, 5]]
levels(build([]))  # returns []

The drawing shows the first tree. In the second example 4 and 5 are on the same level even though they have different parents.

Constraints

  • 0 to 2,000 nodes; values are integers, including 0 and negative numbers.

Ready?

Accept the challenge to start writing. A small timer counts the time this page is in view.

Output appears here.