Leetcode: N-ary Tree Preorder Traversal

N-ary Tree Preorder Traversal

Similar Problems:

Given an n-ary tree, return the preorder traversal of its nodes’ values.

For example, given a 3-ary tree:

Leetcode: N-ary Tree Postorder Traversal

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

Note: Recursive solution is trivial, could you do it iteratively?

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.

  • Solution: recursive
## Blog link: https://code.dennyzhang.com/n-ary-tree-preorder-traversal
## Basic Ideas:
## Complexity:
# Definition for a Node.
class Node(object):
    def __init__(self, val, children):
        self.val = val
        self.children = children
class Solution(object):
    def preorder(self, root):
        :type root: Node
        :rtype: List[int]
        if root is None: return []
        res = [root.val]
        for child in root.children:
            res += self.preorder(child)
        return res

Share It, If You Like It.

Leave a Reply

Your email address will not be published.