N-ary Tree Preorder Traversal

Problem Id: 589 Difficulty: Easy Tag: Tree


Intuition

Just do the simple preorder traversal. The only difference between binary tree preorder traversal is that we need to traversal all the children of each node.

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]:
        order = []
        self._helper(root, order)
        return order

    def _helper(self, node, order):
        if node is None:
            return

        order.append(node.val)
        for child in node.children:
            self._helper(child, order)