难度: Easy
原题连接
内容描述
Given an n-ary tree, return the preorder traversal of its nodes' values.
For example, given a 3-ary tree:
Return its preorder traversal as: [1,3,5,6,2,4].
Note:
Recursive solution is trivial, could you do it iteratively?
思路 1 - 时间复杂度: O(N)- 空间复杂度: O(1)******
递归,beats 74.77%
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if not root:
return []
res = []
res.append(root.val)
for child in root.children:
res.extend(self.preorder(child))
return res
思路 2 - 时间复杂度: O(N)- 空间复杂度: O(1)******
迭代,beats 95.28%
class Solution(object):
def preorder(self, root):
"""
:type root: Node
:rtype: List[int]
"""
if not root:
return []
res, stack = [], [root]
while stack:
node = stack.pop()
res.append(node.val)
for child in node.children[::-1]:
stack.append(child)
return res