N-ary Tree Preorder Traversal — LeetCode 589 Python Solution
EasyStackTreeDepth-First Search
- Problem
- #589
- Pattern
- Stack
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Given the root of an n-ary tree, return the preorder traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal.
Example
- Input
- root = [1,null,3,2,4,null,5,6]
- Output
- [1,3,5,6,2,4]
Python solution
Python
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def preorder(self, root: "Node") -> List[int]:
def dfs(root):
if root is None:
return
ans.append(root.val)
for child in root.children:
dfs(child)
ans = []
dfs(root)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 589. N-ary Tree Preorder Traversal is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Stack.
The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 589. N-ary Tree Preorder Traversal?
- LeetCode 589. N-ary Tree Preorder Traversal is rated Easy on LeetCode.
- What is the time complexity of LeetCode 589. N-ary Tree Preorder Traversal?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 589. N-ary Tree Preorder Traversal?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 589. N-ary Tree Preorder Traversal cover?
- LeetCode 589. N-ary Tree Preorder Traversal is tagged Stack, Tree and Depth-First Search on LeetCode.