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]

 

相关文章:

  • 2021-07-26
  • 2022-02-10
  • 2021-09-16
  • 2021-10-24
  • 2021-12-15
  • 2021-11-16
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-27
  • 2022-12-23
  • 2022-12-23
  • 2021-06-28
  • 2021-10-19
  • 2021-07-13
  • 2022-02-10
相关资源
相似解决方案