Leetcode 775 Solution

This article provides solution to leetcode question 775 (n-ary-tree-preorder-traversal)

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

Solution

"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""

class Solution:
    def preorder(self, root: 'Node') -> List[int]:
        if not root:
            return

        s = [(root, -1)]
        ans = []

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

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

        return ans