Group a Tree's Values Level by Level

Implement levelGroups

You are given the root of a binary tree. Group the node values by level: the root alone forms the first group, its children (left to right) the second, their children the third, and so on. Return the groups from the top level to the bottom level.

You can find the groups by re-walking the tree once per level, but a queue does it in a single pass: it always holds the nodes of the level being processed, and the nodes it collects behind them form the next level.

Example 1:

Input: root = [21,8,30,5,13,null,34,3]

Output: [[21],[8,30],[5,13,34],[3]]

Example 2:

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

Output: [[4],[9],[2]]

Example 3:

Input: root = []

Output: []

+ 11 hidden test cases run on Submit.

Constraints:

  • ●0 ≤ number of nodes ≤ 100
  • ●−100 ≤ node.val ≤ 100
  • ●The tree is given as its root node (null for an empty tree); each node has a val, a left child and a right child
  • ●Return one list per level of the tree, from the root level downwards; inside a level, list the values from left to right. An empty tree gives an empty list of levels

root =

[21, 8, 30, 5, 13, null, 34, 3]