天天看點

590. N叉樹的後序周遊

給定一個 N 叉樹,傳回其節點值的後序周遊。

例如,給定一個 

3叉樹

 :
590. N叉樹的後序周遊
傳回其後序周遊: 

[5,6,3,2,4,1]

.

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

class Solution:
    def postorder(self, root: 'Node') -> List[int]:
        res=[]
        def helper(root):
            if not root:
                return None
            children=root.children
            for i in children:
                helper(i)
            res.append(root.val)
        helper(root)
        return res      
"""
# Definition for a Node.
class Node:
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""

class Solution:
    def postorder(self, root: 'Node') -> List[int]:
        if not root:
            return []
        res=[]
        stack=[root]
        while stack:
            node=stack.pop()
            res.append(node.val)
            for i in node.children:
                stack.append(i)
        return res[::-1]