#589
N-ary Tree Preorder Traversal
EasyStackTreeDepth-First SearchDepth-First Search (DFS)Stack
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 solution uses an iterative approach with a stack, which allows us to avoid the overhead of recursive function calls and manage the traversal explicitly.
⚙️
Algorithm
3 steps- 1Step 1: Initialize a stack and push the root node onto it.
- 2Step 2: While the stack is not empty, pop the top node, add its value to the result list.
- 3Step 3: Push all children of the popped node onto the stack in reverse order.
solution.py17 lines
1# Full working Python code
2class Node:
3 def __init__(self, val=None, children=None):
4 self.val = val
5 self.children = children if children is not None else []
6
7class Solution:
8 def preorder(self, root):
9 if not root:
10 return []
11 result = []
12 stack = [root]
13 while stack:
14 node = stack.pop()
15 result.append(node.val)
16 stack.extend(reversed(node.children))
17 return resultℹ
Complexity note: The optimal solution runs in linear time because we visit each node exactly once, and the space complexity is linear due to the stack storing nodes.
- 1Understanding tree traversal patterns is crucial for solving tree-related problems.
- 2Iterative solutions often provide better performance and avoid stack overflow issues with deep recursion.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.