N-ary tree level order traversal

September 1, 2022

tree

Problem URL: N-ary tree level order traversal

We will run BFS in each level and append the values in a result list, and return the list when traversal is done.

"""
# 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]]:
        if not root:
            return []

        q = collections.deque([root])
        res = []
        while q:
            qLen = len(q)
            level = []
            for _ in range(qLen):
                node = q.pop()
                level.append(node.val)
                for child in node.children:
                    q.appendleft(child)
            res.append(level)
        return res

Time Complexity: O(n)
Space Complexity: O(n)