递归法
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
class Solution:
def preorder(self, root: 'Node') -> List[int]:
arr = []
def dfs(node):
if node:
arr.append(node.val)
for child in node.children:
dfs(child)
dfs(root)
return arr
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/3a98ebf7c34e0e5d94720852b68b76c2.png)
非递归法
class Solution:
def preorder(self, root: 'Node') -> List[int]:
if not root:
return []
stack = [root]
display = []
while stack:
node = stack.pop()
display.append(node.val)
stack.extend(node.children[::-1])
return display
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/36b319bba77c0a5af01b8bdb2a21dcbf.png)