题目
Given the root of an n-ary tree, return the preorder 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 preorder(self, root: 'Node') -> List[int]:
def dfs(root):
if root:
res.append(root.val)
for child in root.children:
dfs(child)
res = []
dfs(root)
return res