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