590. N叉树的后序遍历



# Definition for a Node.
class Node(object):
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children

方法一:迭代

class Solution(object):
    # 迭代
    def postorder(self, root):
        """
        :type root: Node
        :rtype: List[int]
        """
        res = []
        if not root:
            return res
        stack = [root]
        while stack:
            curr = stack.pop()
            res.append(curr.val)
            stack += curr.children
        return res[::-1]

方法二:递归

class Solution(object):
    # 递归
    def postorder(self, root):
        """
        :type root: Node
        :rtype: List[int]
        """
        res = []
        if not root:
            return res
        # 递归遍历子树
        for tNode in root.children:
            res += self.postorder(tNode)
        # 加根节点
        res.append(root.val)
        return res
posted @ 2020-08-30 17:23  人间烟火地三鲜  阅读(139)  评论(0编辑  收藏  举报