Posted on 2022-11-13 18:58
Uriel 阅读(43)
评论(0) 编辑 收藏 引用 所属分类:
搜索 、
数据结构 、
闲来无事重切Leet Code
深度优先先序遍历一棵树
1 #589
2 #Runtime: 43 ms
3 #Memory Usage: 16.4 MB
4
5 """
6 # Definition for a Node.
7 class Node(object):
8 def __init__(self, val=None, children=None):
9 self.val = val
10 self.children = children
11 """
12
13 class Solution(object):
14 def DFS(self, root):
15 if not root:
16 return
17 self.ans.append(root.val)
18 for i in root.children:
19 self.DFS(i)
20
21 def preorder(self, root):
22 """
23 :type root: Node
24 :rtype: List[int]
25 """
26 self.ans = []
27 self.DFS(root)
28 return self.ans