#429
N-ary Tree Level Order Traversal
MediumTreeBreadth-First SearchBreadth-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 traversal of the tree. This allows us to efficiently process nodes level by level, ensuring we capture all nodes at each level before moving to the next.
⚙️
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 all its children.
- 4Step 4: After processing all nodes at the current level, add the level list to the result.
solution.py23 lines
1# Full working Python code
2from collections import deque
3
4class Node:
5 def __init__(self, val=None, children=None):
6 self.val = val
7 self.children = children if children is not None else []
8
9class Solution:
10 def levelOrder(self, root):
11 if not root:
12 return []
13 result = []
14 queue = deque([root])
15 while queue:
16 level_size = len(queue)
17 level_nodes = []
18 for _ in range(level_size):
19 node = queue.popleft()
20 level_nodes.append(node.val)
21 queue.extend(node.children)
22 result.append(level_nodes)
23 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 the current level.
- 1Breadth-first search is ideal for level order traversal.
- 2Using a queue ensures we process nodes level by level.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.