Binary Tree Level Order Traversal

Binary Tree Level Order Traversal

Given the root of a binary tree, return its level order traversal as a nested list. Each sublist should contain the node values at a specific level, ordered from left to right.

Binary tree level order traversal problem

Example 1:

Binary Tree Level Order Traversal Question

Example 2:

  • Input: root = [1]
  • Output: [[1]]

Example 3:

  • Input: root = [ ]
  • Output: [ ]

Constraints:

  • 0 <= Number of nodes in both trees <= 1000.
  • -1000 <= Node.val <= 1000

Hints to Solve Binary Tree Level Order Traversal

Recommendation for Time and Space Complexity:

Aim for a solution with O(n) time and O(n) space, where n is the total number of nodes in the tree.

Hint 1 :

Level of a tree consists of all nodes at the same distance from the root. Can you think of a way to traverse the tree level by level instead of diving deeper?

Hint 2 :

Use the Breadth First Search (BFS) algorithm to traverse the tree level by level. BFS relies on a queue, where at each step, nodes are processed, and their left and right children are added to the queue. This ensures all levels are explored sequentially.

Hint 3 :

Number of queue iterations equals the number of levels in the tree. For each level, process all nodes currently in the queue and add their values to the result. This way, nodes from each level are grouped together.

There are mainly 2 approach to solve this problem:

  1. Depth First Search Method (DFS)
  2. Breadth First Search Method (BFS)

1. Depth First Search Method

Use recursion to traverse the tree depth-wise while keeping track of the current level. Add node values to the corresponding level in the result list as you visit each node.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

2. Breadth First Search Method

Traverse the tree level by level using a queue. Process all nodes at the current level, add their values to the result list, and enqueue their children for the next level.

  • Time complexity: O(n)
  • Space complexity: O(n)

Code

More Articles