Leetcode 776 Solution

This article provides solution to leetcode question 776 (n-ary-tree-postorder-traversal)

https://leetcode.com/problems/n-ary-tree-postorder-traversal

Solution

"""
# 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

        s = [(root, 0)]
        ans = []

        while s:
            node, i = s.pop()

            if i < len(node.children):
                s.append((node, i + 1))
                s.append((node.children[i], 0))
            elif i == len(node.children):
                ans.append(node.val)

        return ans