\"\"\"# Definition for a Node.
class Node( ):
    def __init__(self, val, children):
        self.val = val
        self.children = children
\"\"\"
class Solution( ):
    def preorder(self, root):
        \"\"\"
        :type root: Node
        :rtype: List[int]
        \"\"\"
        if not root:
            return []
        result=[]
        result.append(root.val)
        if not root.children:
            return result
        for child in root.children:
            result+=self.preorder(child)   #两个列表相加,就是一个列表
        return result
        #(递归算法)

执行用时: 144 ms, 在N-ary Tree Preorder Traversal的Python提交中击败了92.31% 的用户

\"\"\"
# Definition for a Node.
class Node( ):
    def __init__(self, val, children):
        self.val = val
        self.children = children
\"\"\"
class Solution( ):         #迭代算法
    def preorder(self, root):
        \"\"\"
        :type root: Node
        :rtype: List[int]
        \"\"\"
        if not root:
            return []
        result=[]
        stack=[]                    #临时存储节点
        stack.append(root)
        while stack:
            curr=stack.pop()
            result.append(curr.val)
            if curr.children:
                curr.children.reverse()
                stack+=curr.children
        return result

执行用时: 144 ms, 在N-ary Tree Preorder Traversal的Python提交中击败了92.31% 的用户

 

收藏 打印