Skip to content

Latest commit

 

History

History
102 lines (52 loc) · 1.39 KB

0590._N-ary_Tree_Postorder_Traversal.md

File metadata and controls

102 lines (52 loc) · 1.39 KB

590. N-ary Tree Postorder Traversal

难度: Easy

刷题内容

原题连接

内容描述

Given an n-ary tree, return the postorder traversal of its nodes' values.

For example, given a 3-ary tree:

 



 

Return its postorder traversal as: [5,6,3,2,4,1].

 
Note:

Recursive solution is trivial, could you do it iteratively?

解题方案

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

递归,beats 93.73%

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

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

迭代,beats 93.73%

class Solution(object):
    def postorder(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:
                stack.append(child)
        return res[::-1]