Binary Tree Level Order Traversal

MediumTrees

Given the root of a binary tree, return its values level by level: an array with one array per level, from the root down, each listing that level’s values from left to right. An empty tree gives [].

On this page a tree is written in level order, top to bottom and left to right, with null where a child is missing: [6, 3, 8, 1] is 6 with children 3 and 8, and 3 with a left child 1.

Examples

Example 1
Input:  root = [8, 4, 12, null, 6, 10]
Output: [[8], [4, 12], [6, 10]]

6 is the right child of 4 and 10 the left child of 12, so the third level reads 6, 10.

Example 2
Input:  root = [4, null, 9, 2]
Output: [[4], [9], [2]]

Each level holds one node, so each inner array has one value.

Constraints

  • The tree has 0 to 2000 nodes.
  • -1000 ≤ node.val ≤ 1000

Stuck?

Hint 1

Visit the nodes breadth first with a queue: each node’s children join the back of the queue, so the levels come out in order.

Hint 2

Before you read a level, note how many nodes the queue holds right then. Take exactly that many: they are the level, and the children they add make up the next one.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 9 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur