Back

Advanced Trees (Hard) / 244. Level Order Traversal

00:00
1/5

244. Level Order Traversal

Hard

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).

Example:

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

    BFS Approach: Level order traversal is essentially Breadth-First Search (BFS).

  • 2

    Queue: Use a queue to keep track of nodes.

  • 3

    Level Tracking:

  • 4

    Iterate while the queue is not empty.

  • 5

    Get the current size of the queue (number of nodes in the current level).

  • 6

    Iterate through that number of nodes, processing them and adding their children to the queue.

  • 7

    Store the values of the current level in a list.

  • 8

    Result: Append each level's list to the final result.

PYTHON PLAYGROUND
PYTHON PLAYGROUND
⏳ Loading editor…