MediumTreeBreadth-First SearchBinary Tree

Binary Tree Level Order Traversal

LeetCode
1 approach, code in all languages

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now