题目要求
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
原文地址:https://www.cnblogs.com/yao1996/p/10358663.html
时间: 2024-10-24 04:24:33