Skip to content

Latest commit

 

History

History
78 lines (52 loc) · 1.36 KB

0589._N-ary_Tree_Preorder_Traversal.md

File metadata and controls

78 lines (52 loc) · 1.36 KB

589. N-ary Tree Preorder Traversal

难度: Easy

刷题内容

原题连接

内容描述

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].

 

Note:

Recursive solution is trivial, could you do it iteratively?

解题方案

思路 1 - 时间复杂度: O(N)- 空间复杂度: O(1)******

递归,beats 74.77%

class Solution(object):
    def preorder(self, root):
        """
        :type root: Node
        :rtype: List[int]
        """ 
        if not root:
            return []
        res = []
        res.append(root.val)
        for child in root.children:
            res.extend(self.preorder(child))
        return res

思路 2 - 时间复杂度: O(N)- 空间复杂度: O(1)******

迭代,beats 95.28%

class Solution(object):
    def preorder(self, root):
        """
        :type root: Node
        :rtype: List[int]
        """
        if not root:
            return []
        res, stack = [], [root]
        while stack:
            node = stack.pop()
            res.append(node.val)
            for child in node.children[::-1]:
                stack.append(child)
        return res