All problems

Binary Tree Level Order Traversal

Medium · tree bfs

You are given the root of a binary tree. Return its values level by level: one list for each depth, starting with the root's level and moving down.

Inside each level, list the values from left to right. The result is a list of lists, so result[0] is [root.val], result[1] holds the root's children, and so on. An empty tree returns an empty list [].

Examples

Example 1

Input: root = [3, 9, 20, null, null, 15, 7]

Output: [[3], [9, 20], [15, 7]]

3 is the root. 9 and 20 are its children. 15 and 7 are the children of 20.

Example 2

Input: root = [1, 2, 3, 4, null, null, 5]

Output: [[1], [2, 3], [4, 5]]

4 hangs under the left child and 5 under the right one, but both sit on level 2, so they share a list.

Example 3

Input: root = []

Output: []

There are no levels at all, so there are no lists.

Constraints