Leetcode: N-ary Tree Postorder Traversal

N-ary Tree Postorder Traversal



Similar Problems:


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

For example, given a 3-ary tree:

Leetcode: N-ary Tree Postorder Traversal

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

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-postorder-traversal
## Basic Ideas:
## Complexity: Time O(n), Space O(n)
"""
# Definition for a Node.
class Node(object):
    def __init__(self, val, children):
        self.val = val
        self.children = children
"""
class Solution(object):
    def postorder(self, root):
        """
        :type root: Node
        :rtype: List[int]
        """
        if root == None: return []
        res = []
        for node in root.children:
            res += self.postorder(node)
        res.append(root.val)
        return res
linkedin
github
slack

Share It, If You Like It.

Leave a Reply

Your email address will not be published.