Uriel's Corner

Research Associate @ Harvard University / Research Interests: Computer Vision, Biomedical Image Analysis, Machine Learning
posts - 0, comments - 50, trackbacks - 0, articles - 594
深度优先先序遍历一棵树

 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

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   博问   Chat2DB   管理