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]

 

posted @ 2019-04-20 18:02  周洋  阅读(121)  评论(0编辑  收藏  举报