N-ary Tree Level Order Traversal — LeetCode 429 Python Solution

MediumTreeBreadth-First Search
Problem
#429
Reading time
4 min

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

Python
"""
# 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 ans

Complexity

MeasureComplexity
TimeO(n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview