Skip to content

Latest commit

 

History

History
39 lines (30 loc) · 785 Bytes

File metadata and controls

39 lines (30 loc) · 785 Bytes

590 N-ary Tree Postorder Traversal

Description

link


Solution

  • N-ary Tree Traversal
  • Remember to reverse the final answer for stack(first in last out)

Code

Complexity T : O(N) M : O(n)

"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""
class Solution:
    def postorder(self, root: 'Node') -> List[int]:
        if not root:
            return []
        stack = [root]
        res = []
        while stack:
            node = stack.pop()
            res.append(node.val)
            stack += [child for child in node.children if child]
        return res[::-1]