Practice · Trees · 7 of 12

Binary Tree Level by Level

You are given root, the root of a binary tree (or nothing, for an empty tree).

Return its values level by level: a list with one inner list per level, from the root's level downwards, each holding that level's values from left to right. An empty tree gives [].

Trees are written in level order, row by row from the top, with null where a node is missing: [4, 2, 7, null, 3] is 4 at the root, 2 and 7 below it, and 3 as the right child of 2.

Example 1

Input
root = [6, 2, 8, 1, 4, null, 9]
Output
[[6], [2, 8], [1, 4, 9]]

Example 2

Input
root = [1, null, 2, 3]
Output
[[1], [2], [3]]
Each level of this tree has a single node.

Constraints

  • The tree holds 0 to 2000 nodes.
  • Every value is between −1000 and 1000.