\"\"\"# 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% 的用户
继续阅读与本文标签相同的文章
下一篇 :
Nginx服务器的简明架构
-
干货送上,小程序运动步数实战分享
2026-05-19栏目: 教程
-
ZAO 背后的深度学习算法原理浅析
2026-05-19栏目: 教程
-
应用优雅上下线
2026-05-19栏目: 教程
-
FFMPEG常用命令收录(持续更新)
2026-05-19栏目: 教程
-
OpenSSL 1.1.1的裁剪
2026-05-19栏目: 教程
