589. N叉树的前序遍历



方法一:迭代

class Solution(object):
    # 迭代
    def preorder(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[::-1]
        return res

方法二:递归

class Solution(object):
    # 递归
    def preorder(self, root):
        """
        :type root: Node
        :rtype: List[int]
        """
        if not root:
            return []
        ans = []
        return self.dfs(root, ans)

    def dfs(self, root, ans):
        ans.append(root.val)
        for node in root.children:
            self.dfs(node, ans)
        return ans
原文地址:https://www.cnblogs.com/panweiwei/p/13585857.html