Skip to main content
CodeOath
← All problems

Problem

Binary Tree Level Order Traversal

Medium
  • trees
  • bfs

Return the values of the binary tree root one level at a time. The first inner array holds the root, the next holds its children from left to right, and so on down the tree. The result is an array of arrays with one entry per level. An empty tree gives [].

Trees in this problem are written as level-order arrays: the root first, then each level from left to right. null marks a missing child, and a missing child has no entries beneath it. Trailing nulls are omitted.

Example 1
Input
root = [5, 2, 9, 1, 3, null, 8]
Output
[[5], [2, 9], [1, 3, 8]]
Explanation

5 is the root and 2 and 9 are its children. The last level holds 1 and 3, the children of 2, and 8, the child of 9.

Example 2
Input
root = [1, 2, 3, 4, null, null, 5]
Output
[[1], [2, 3], [4, 5]]
Explanation

4 and 5 have different parents but sit on the same level, so they share one inner array.

Example 3
Input
root = []
Output
[]
Explanation

an empty tree has no levels.

Tab indents. Press Esc, then Tab to leave the editor.

Run your code to see every test here. Nothing is submitted or recorded.