Leetcode 590. N-ary Tree Postorder Traversal

Posted 周洋的Blog

tags:

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

DFS,递归或者栈实现.

"""
# Definition for a Node.
class Node:
    def __init__(self, val, children):
        self.val = val
        self.children = children
"""
class Solution:
    def postorder(self, root: Node) -> List[int]:
        if not root:
            return []
        if not root.children:
            return [root.val]
        ans=[]
        stack=[root]
        node=stack[-1]
        mark={}
        while stack:
            if (not node.children) or (mark.get(node.children[0],0)==1):
                pop=stack.pop()
                mark[pop]=1
                ans.append(pop.val)
                if not stack:
                    break
                node=stack[-1]
            else:
                stack.extend(reversed(node.children))
                node = stack[-1]
        return ans
"""
# Definition for a Node.
class Node:
    def __init__(self, val, children):
        self.val = val
        self.children = children
"""
class Solution:
    def postorder(self, root: Node) -> List[int]:
        if not root:
            return []
        if not root.children:
            return [root.val]
        ans=[]
        for c in root.children:
            ans.extend(self.postorder(c))
        return ans+[root.val]

 

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

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

leetcode590. N-ary Tree Postorder Traversal

(N叉树 递归) leetcode 590. N-ary Tree Postorder Traversal

[LeetCode] 590. N-ary Tree Postorder Traversal_Easy

leetcode 590.N-ary Tree Postorder Traversal N叉树的后序遍历

590. N-ary Tree Postorder Traversal