429. N-ary Tree Level Order Traversal
- N-ary Tree Level Order Traversal python solution
题目描述
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).
解析
解题思路就是逐层递归,见代码
class Solution:
def levelOrder(self, root: 'Node') -> List[List[int]]:
queue = [root] if root else []
result = []
while queue:
result.append([node.val for node in queue])
queue = [child for node in queue for child in node.children]
return result
Reference
https://leetcode.com/problems/n-ary-tree-level-order-traversal/discuss/307276/Python-easy-6-liner-with-commentary