N-ary Tree Level Order Traversal — LeetCode 429 Python Solution
- Problem
- #429
- Pattern
- Tree Traversal
- Reading time
- 4 min
- Source
- leetcode.com
The problem
Given an n-ary tree, return the level order traversal of its nodes' values. Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
Example
- Input
- root = [1,null,3,2,4,null,5,6]
- Output
- [[1],[3,2,4],[5,6]]
Python solution
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
ans = []
if root is None:
return ans
q = deque([root])
while q:
t = []
for _ in range(len(q)):
root = q.popleft()
t.append(root.val)
q.extend(root.children)
ans.append(t)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Tree Traversal
Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 429. N-ary Tree Level Order Traversal is filed here because LeetCode tags it Tree, which is the vocabulary this hub collects.
The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 429. N-ary Tree Level Order Traversal?
- LeetCode 429. N-ary Tree Level Order Traversal is rated Medium on LeetCode.
- What is the time complexity of LeetCode 429. N-ary Tree Level Order Traversal?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 429. N-ary Tree Level Order Traversal?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 429. N-ary Tree Level Order Traversal cover?
- LeetCode 429. N-ary Tree Level Order Traversal is tagged Tree and Breadth-First Search on LeetCode.