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

 

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐