CodingNodes / Trees / Binary Tree Level Order Traversal System design Space play · ←→ step · R restart

Problem

Given the root of a binary tree, return its node values grouped by level: first the root, then its children from left to right, then the next level, and so on.

The tree is given in level order, with null for a missing child. An empty tree gives an empty list.

Constraints

  • 0 ≤ number of nodes ≤ 2000
  • -1000 ≤ Node.val ≤ 1000

Examples: pick one to animate

Solutions

TimeO(n) SpaceO(w)

Time: Every node is added to the queue once and taken out once, with constant work each time.

Space: The queue holds at most one or two levels at a time, so it is as large as the widest level, w. That can reach n/2. The result itself holds n values.

Use a queue so nodes come out level by level. At the start of each round the queue holds exactly one level, so save its size first. Take that many nodes, collect their values into a list, and queue their children for the next round. Then the finished list is one level of the answer.