题目
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).
解题思路
从根开始按层进行BFS遍历,把每层的数值存到结果里
代码
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
if not root:
return []
q = [root]
res = []
while q:
res.append([])
next_level = []
for node in q:
res[-1].append(node.val)
for child in node.children:
next_level.append(child)
q = next_level
return res