Python实现"N叉树的前序遍历"的两种方法

给定一颗n叉树,返回对它节点值的前序遍历
例如,给定一个3叉树:

返回它的前序遍历为:[1,3,5,6,2,4]
注意:递归很简单,请尝试用迭代的方法完成

1、迭代

def preorder(self, root):
        """
        :type root: Node
        :rtype: List[int]
        """
        if not root:
            return []
        gBack = []
        nodeList = [root]
        while nodeList:
            node = nodeList.pop(0)
            if node:
                gBack.append(node.val)
                for i in node.children[::-1]:
                    nodeList.insert(0, i)
        return gBack

2、递归

def preorder(self, root):
        """
        :type root: Node
        :rtype: List[int]
        """
        if not root:
            return []
        gBack = [root.val]
        for node in root.children:
            gBack += self.preorder(node)
        return gBack

算法题来自:https://leetcode-cn.com/problems/n-ary-tree-preorder-traversal/description/

你可能感兴趣的:(Algorithms)