[LeetCode&Python] Problem 590. N-ary Tree Postorder Traversal

Posted chiyeung

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode&Python] Problem 590. N-ary Tree Postorder Traversal相关的知识,希望对你有一定的参考价值。

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

 

For example, given a 3-ary tree:

技术分享图片

 

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

 

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

 

Recursion Solution:

"""
# 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]
        """
        def dfs(r):
            if not r:
                return
            else:
                for c in r.children:
                    dfs(c)
                result.append(r.val)
        
        result=[]
        dfs(root)
        return result

  

Iteration Solution:

"""
# 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 not root:
            return []
        
        # We can use a deque to store the solution
        res=collections.deque()
        # We use stack to store all the node
        #Every time, we only need to pick the top node in the stack
        #and store its value in res
        #And then we store its children in the stack. The right-most
        #child is stored in the top.
        #If our stack is empty, we finish our job.
        stack=[root]
        
        while stack:
            u=stack.pop()
            res.appendleft(u.val)
            for c in u.children:
                stack.append(c)
                
        #change deque back to list
        return list(res)

  

以上是关于[LeetCode&Python] Problem 590. N-ary Tree Postorder Traversal的主要内容,如果未能解决你的问题,请参考以下文章

C++&Python描述 LeetCode C++&Python描述 LeetCode 剑指 Offer 22. 链表中倒数第k个节点

[LeetCode&Python] Problem 202. Happy Number

[LeetCode&Python] Problem 520. Detect Capital

[LeetCode&Python] Problem 383. Ransom Note

[LeetCode&Python] Problem 458. Poor Pigs

[LeetCode&Python] Problem 682. Baseball Game