1. 程式人生 > >LeetCode 589 N-ary Tree Preorder Traversal 解題報告

LeetCode 589 N-ary Tree Preorder Traversal 解題報告

append 遞歸 遍歷 lee tco pytho its not list

題目要求

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

LeetCode 589 N-ary Tree Preorder Traversal 解題報告