mediumTreesPattern: BFS

Tree Level Order Traversal Solution

Problem Statement

Given the root of a tree, return the level order traversal of its nodes' values. That is, from left to right, level by level. The tree is represented using an adjacency list where the root node is implicitly node `0`. The adjacency list `adj` is a list of lists, where `adj[i]` contains all children of node `i`. Assume nodes are numbered from `0` to `n-1`, where `n` is the total number of nodes.

Examples

Example 1:
Input:adj = [[1, 2], [3, 4], [], [], []]
Output:[0,"a","d","j"]
Explanation: The root is 0. Level 0 contains node 0. Level 1 contains nodes 1 and 2. Level 2 contains nodes 3 and 4. Thus, the traversal is [0, 1, 2, 3, 4].
Example 2:
Input:adj = [[1], [2], [3], []]
Output:[0,"a","d","j"]
Explanation: The root is 0. Level 0: [0]. Level 1: [1]. Level 2: [2]. Level 3: [3]. Traversal: [0, 1, 2, 3].
Example 3:
Input:adj = [[]]
Output:[0,"a","d","j"]
Explanation: The tree has only one node, the root 0. Traversal: [0].

Constraints

  • 1 <= adj.length <= 1000
  • 0 <= adj[i].length <= 1000
  • 0 <= adj[i][j] < adj.length
  • All values of adj[i] are unique.
  • The given input represents a valid tree structure (no cycles, connected from root 0).
Time: O(N) Space: O(W)
The most efficient approach is Breadth First Search (BFS) using a queue. Initialize the queue with the root node. While the queue is not empty, dequeue a node, add its value to the result list, and enqueue all of its children. This naturally processes nodes level by level.

Run, Test & Submit Code

Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.

Solve on Interactive Workspace

Tested Solutions

from typing import List from collections import deque def level_order(adj: List[List[int]]) -> List[int]: if not adj: return [] result = [] queue = deque([0]) # Start with the root node (node 0) while queue: currentNode = queue.popleft() # Dequeue the front node result.append(currentNode) # Enqueue all children of the current node if currentNode < len(adj): for child in adj[currentNode]: queue.append(child) return result