Start learning free

LESSON 459 OF 635 · BINARY TREES

Level Order Tree Traversal

Practice O(n)

You get the root of a binary tree. Return its values row by row, as a list with one list per row.

Start with the root's row and go down. List each row's values from left to right.

In the examples, each tree is written row by row from the top. Each row goes left to right. None marks a missing child.

Example 1:

Input: [8,3,5,None,6,2,4]
       8
      / \
     /   \
    3     5
     \   / \
      6 2   4

Output:
[
  [8],
  [3, 5],
  [6, 2, 4]
]
Explanation: The bottom row starts with 6, a child of 3.
Then come 2 and 4, the children of 5.

Example 2:

Input: [4,None,7,1]
  4
   \
    7
   /
  1

Output:
[
  [4],
  [7],
  [1]
]
Explanation: Each row has just one node.
It doesn't matter that 7 is a right child and 1 is a left child.

Constraints:

  • The tree has 1 to 1,000 nodes.
  • Each value is a whole number from 1 to 1,000.
  • All values are different.
STEP 1 OF 9
    Ctrl + Enter to check