题目描述:
解题过程:
题目提示使用递归,可惜自己对递归和二叉树N叉树还是了解不多QAQ,评论区代码如下:
"""
# Definition for a Node.
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution:
def preorder(self, root: 'Node') -> List[int]:
if not root:
return []
result=[root.val]
if root.children:
for each in root.children:
result.extend(self.preorder(each))
return result
总结:
- 递归和二叉树挺重要,有时间看一下算法和数据结构;
- extend()作用为在列表末尾一次性增加多个值,此处如果使用append()的话,会使输出数据变为高维数据。