#102
Binary Tree Level Order Traversal
MediumTreeBreadth-First SearchBinary TreeBreadth-First SearchQueue
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n)Space O(n)
The optimal approach uses a queue to perform a breadth-first search (BFS) on the tree. This allows us to process each level of the tree in a single pass, making it much more efficient.
⚙️
Algorithm
4 steps- 1Step 1: Initialize a queue and add the root node to it.
- 2Step 2: While the queue is not empty, determine the number of nodes at the current level.
- 3Step 3: Dequeue each node, add its value to the current level list, and enqueue its children.
- 4Step 4: After processing all nodes at the current level, add the level list to the result.
solution.py25 lines
1# Full working Python code
2from collections import deque
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 = []
17 for _ in range(level_size):
18 node = queue.popleft()
19 level.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)
25 return resultℹ
Complexity note: The time complexity is O(n) because we visit each node exactly once. The space complexity is O(n) due to the queue storing nodes at each level.
- 1Using a queue allows for efficient level-wise traversal.
- 2Understanding tree depth helps in visualizing the traversal.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.