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 1:
Input: root = [3,9,20,null,null,15,7] Output: [[3],[9,20],[15,7]]
Example 2:
Input: root = [1] Output: [[1]]
Example 3:
Input: root = [] Output: []
Constraints:
[0, 2000].-1000 <= Node.val <= 1000The key idea behind Binary Tree Level Order Traversal is to process nodes level by level, starting from the root and moving downward. The most efficient strategy uses Breadth-First Search (BFS) with a queue. BFS naturally explores nodes in layers, which aligns perfectly with the requirement to group nodes by their depth in the tree.
You begin by pushing the root node into a queue. For each iteration, process all nodes currently in the queue—these represent a single level. While processing them, collect their values and push their left and right children into the queue for the next level. This ensures nodes are visited in the exact order required for level-wise traversal.
An alternative idea is to use Depth-First Search (DFS) with recursion while tracking the current depth and storing values in a list corresponding to that level. However, BFS is generally the most intuitive and commonly used approach for this problem. The traversal touches each node exactly once, giving efficient performance.
| Approach | Time Complexity | Space Complexity |
|---|---|---|
| Breadth-First Search (Queue) | O(n) | O(n) |
| Depth-First Search with Level Tracking | O(n) | O(n) |
take U forward
Use these hints if you're stuck. Try solving on your own first.
Use a queue to perform BFS.
This approach utilizes a queue to perform a Breadth-First Search (BFS) on the binary tree. Starting from the root, traverse each level of the tree and store values of nodes in separate lists for each level. By using a queue, we can efficiently keep track of nodes at the current level and their respective children for the next level.
Time Complexity: O(n), where n is the number of nodes in the tree because each node is visited once.
Space Complexity: O(n), as we store all nodes at each level in the queue.
1from collections import deque
2
3class TreeNode:
4 def __init__(self, val=0, left=None, right=None):
5 self.val = val
6 self.left = left
7 self.right = right
8
9def levelOrder(root):
10 if not root:
11 return []
12 result = []
13 queue = deque([root])
14 while queue:
15 level_size = len(queue)
16 level_nodes = []
17 for _ in range(level_size):
18 node = queue.popleft()
19 level_nodes.append(node.val)
20 if node.left:
21 queue.append(node.left)
22 if node.right:
23 queue.append(node.right)
24 result.append(level_nodes)
25 return resultWe use a deque from the collections module to easily append and pop nodes from the queue. Starting with the root node if it is not null, we add it to the queue. For each level, determine the number of nodes at that level (i.e., the size of the queue), then iterate over them, adding each node's children to the queue for the next level. Collect and return the node values in a nested list representing each level.
This approach involves using a Depth-First Search (DFS) where we pass along the current level during the recursive calls. By keeping track of the current depth, we can directly add node values to their appropriate level in our result list, creating new levels in our result list as needed.
Time Complexity: O(n) since each node is visited once.
Space Complexity: O(n), considering the space needed for the result and recursive call stack.
1using System;
2using System.Collections.Generic;
3
4public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int x) { val = x; }
}
public class Solution {
public IList<IList<int>> LevelOrder(TreeNode root) {
var levels = new List<IList<int>>();
DFS(root, 0, levels);
return levels;
}
private void DFS(TreeNode node, int level, List<IList<int>> levels) {
if (node == null) return;
if (level == levels.Count)
levels.Add(new List<int>());
levels[level].Add(node.val);
DFS(node.left, level + 1, levels);
DFS(node.right, level + 1, levels);
}
}Watch expert explanations and walkthroughs
Practice problems asked by these companies to ace your technical interviews.
Explore More ProblemsJot down your thoughts, approach, and key learnings
Yes, it can also be solved using Depth-First Search by keeping track of the current depth during recursion. You store node values in a list corresponding to their level. However, BFS is typically simpler and more intuitive for this problem.
Yes, this problem or its variations frequently appear in FAANG and other top tech company interviews. It tests understanding of tree traversal, BFS, and queue-based problem solving.
A queue is the most suitable data structure because it supports the FIFO order required for Breadth-First Search. By pushing child nodes into the queue as you process the current level, you naturally traverse the tree layer by layer.
The optimal approach uses Breadth-First Search (BFS) with a queue. BFS processes nodes level by level, making it ideal for collecting values from each tree level in order. Each node is visited once, resulting in O(n) time complexity.
This C# example employs a recursive DFS method. Starting from the root, if current depth matches the level count, a new level is added. Each node value is added to its respective level list during traversal. The function recursively processes left and then right children, ensuring nodes are placed in their correct depth-lists.