429. N-ary Tree Level Order Traversal
2 years ago in Python
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
class Solution:
# Time Complexity: O(N), N = total nodes in the given tree, we visit each node once
# Space Complexity: O(N), N = total nodes in the given tree, output will be the same len as given total nodes
def levelOrder(self, root: 'Node') -> List[List[int]]:
if not root:
return None
result = []
q = deque([root])
while q:
current_row = []
for _ in range(len(q)):
node = q.popleft()
current_row.append(node.val)
for child in node.children:
q.append(child)
result.append(current_row)
return result