MediumTreeBreadth-First SearchBinary Tree

1 approach, code in every language

Problem description

You are given the root of a binary tree. Return its values grouped by level, where each group holds the values of one depth read from left to right.

The first group contains only the root, the second group contains the root's children, and so on down the tree. The output is a list of lists, one inner list per level, in top-to-bottom order.

This is a classic breadth-first problem: instead of diving deep along one branch, we sweep across the tree one horizontal layer at a time.

Example 1

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

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

Level 0 is the root 3, level 1 is its children 9 and 20, and level 2 is 20's children 15 and 7.

Example 2

Input: root = [1]

Output: [[1]]

A single-node tree produces one level containing just the root.

Constraints

  • The number of nodes in the tree is in the range [0, 2000].
  • -1000 <= Node.val <= 1000

After the pattern

Now solve one you haven't seen.

Cable Splice Depths is our own problem on the technique behind Binary Tree Level Order Traversal: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free