版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/aaa958099161/article/details/86606107
leetcode:589. N-ary Tree Preorder Traversal -python
Given an n-ary tree, return the preorder traversal of its nodes' values.
For example, given a 3-ary
tree:
Return its preorder traversal as: [1,3,5,6,2,4]
题目的意思为:前序遍历树。
Runtime: 132 ms, faster than 100.00% of Python3 online submissions for N-ary Tree Preorder Traversal.
"""
# Definition for a Node.
class Node:
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Solution:
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if root==None:
return []
output = []
self.get_out(output,root)
return output
def get_out(self,output, root):
if root:
output.append(root.val)
if root.children!=None:
for node_child in root.children:
self.get_out(output, node_child)
return output