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:

 

589. N-ary Tree Preorder Traversal -python

 

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

 

相关文章:

  • 2021-10-15
  • 2021-09-22
  • 2022-02-10
  • 2021-10-04
  • 2021-06-28
  • 2021-06-28
  • 2021-11-07
  • 2021-12-15
猜你喜欢
  • 2021-09-16
  • 2021-10-24
  • 2021-11-16
  • 2022-12-23
  • 2022-12-23
  • 2021-07-26
  • 2022-12-23
相关资源
相似解决方案