AlgoMaster Logo

Binary Tree Level Order Traversal

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Iterative using Queue (Breadth-First Search)

Intuition:

The most intuitive way to achieve level order traversal is by using a queue (FIFO) data structure. The idea is to process each level of the binary tree one at a time, adding child nodes to the queue as we go. This way, we ensure nodes are processed level by level.

Steps:

  1. Initialize an empty Queue and an empty list result.
  2. Add the root of the tree to the queue.
  3. While the queue is not empty:
    • Determine the number of nodes at this level (size of the queue).
    • For each node in the current level, remove the node from the queue and add its value to a temporary list.
    • Add the left and right children (if they exist) to the queue.
    • After processing all nodes at this level, add the temporary list to the result.
  4. Finally, return the result list which contains nodes level by level.

Code:

Intuition:

An alternative is to use recursion to perform a depth-first search, keeping track of the depth of the current node. The goal is to add each node to a list that corresponds to its depth level.

Steps:

  1. Define a helper function that:
    • Takes the current node, depth, and the result list.
    • If the current node is null, return immediately.
    • If the current depth matches the size of the result list, create a new list at that depth.
    • Add the current node's value to its corresponding depth in the result list.
    • Recurse deeper into the tree by calling the function for the left and right children.
  2. Call the helper function starting with the root node at depth 0.
  3. Return the result list containing the nodes level by level.

Code: