TIC
The Interns Company

Binary Tree Level Order Traversal

MediumAcceptance: 60.1%

Problem Statement

Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level).

Constraints:

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

Input Format:

  • The root of a binary tree

Output Format:

  • An array where each inner array contains the values from a level of the tree

Examples:

Example 1:

Input:

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

Output:

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

Explanation:

Level order traversal returns the values grouped by level, top to bottom, left to right.

Example 2:

Input:

root = [1]

Output:

[[1]]

Explanation:

A tree with just one node has only one level.

Example 3:

Input:

root = []

Output:

[]

Explanation:

An empty tree has no values.

Solutions

BFS with Queue

Time: O(n)
Space: O(n)

Use a queue to traverse the tree level by level.

Recursive Approach

Time: O(n)
Space: O(n)

Use recursion with a helper function to process each level.

Algorithm Walkthrough

Example input:

Step-by-step execution:

  1. root = [3,9,20,null,null,15,7]
  2. queue = [3], result = []
  3. process level 0: queue = [], currentLevel = [3], result = [[3]]
  4. add children: queue = [9, 20]
  5. process level 1: queue = [], currentLevel = [9, 20], result = [[3], [9, 20]]
  6. add children: queue = [15, 7]
  7. process level 2: queue = [], currentLevel = [15, 7], result = [[3], [9, 20], [15, 7]]
  8. queue is empty, return result = [[3], [9, 20], [15, 7]]

Hints

Hint 1
Use a queue to process nodes level by level.
Hint 2
Keep track of the number of nodes at each level to create sublists.
Hint 3
Consider using a breadth-first search (BFS) approach.

Video Tutorial

Video tutorials can be a great way to understand algorithms visually

Visualization

Visualize the tree and the level-by-level traversal process.

Key visualization elements:

  • current node
  • current level
  • queue state

Implementation Notes

Level order traversal is a breadth-first search (BFS) approach to traversing a tree. It's particularly useful for problems that require processing nodes level by level or finding the shortest path in a tree.