题目要求
Given an n-ary tree, return the preorder traversal of its nodes' values.
题目分析及思路
题目给出一棵N叉树,要求返回结点值的前序遍历。可以使用递归的方法做。因为是前序遍历,所以最开始就加入根结点的值。
python代码
"""
# 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]':
order = []
if not root:
return order
order.append(root.val)
for child in root.children:
order.extend(self.preorder(child))
return order