首页 > 其他 > 详细

Leetcode 590. N-ary Tree Postorder Traversal

时间:2019-04-20 18:26:47      阅读:120      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/zywscq/p/10741936.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!