给定一个 N 叉树,返回其节点值的前序遍历和后序遍历

例如,给定一个 3叉树 :

 

返回其前序遍历: [1,3,5,6,2,4]

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

class Solution(object):
    def preorder(self, root):
        """
        :type root: Node
        :rtype: List[int]
        """
        if root is None:
            return []
        
        stack, output = [root, ], []            
        while stack:
            root = stack.pop()
            output.append(root.val)
            stack.extend(root.children[::-1])
                
        return output

后序遍历

"""
# 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]
        """
        stack,ouput = [root,],[]
        while stack:
            root = stack.pop()
            if root:
                ouput.append(root.val)
            else:
                return
            for i in root.children:
                stack.append(i)
        return ouput[::-1]
原文地址:https://www.cnblogs.com/ghl666/p/13520886.html