Uriel's Corner

Research Associate @ Harvard University / Research Interests: Computer Vision, Biomedical Image Analysis, Machine Learning
posts - 0, comments - 50, trackbacks - 0, articles - 594
求二叉树每一层的最大值,按层BFS

 1 #515
 2 #Runtime: 26 ms (Beats 68.6%)
 3 #Memory: 17.7 MB (Beats 71.73%)
 4 
 5 # Definition for a binary tree node.
 6 # class TreeNode(object):
 7 #     def __init__(self, val=0, left=None, right=None):
 8 #         self.val = val
 9 #         self.left = left
10 #         self.right = right
11 class Solution(object):
12     def largestValues(self, root):
13         """
14         :type root: TreeNode
15         :rtype: List[int]
16         """
17         if not root:
18             return []
19         q = deque([root])
20         ans = []
21         while q:
22             sz = len(q)
23             t = float('-inf')
24             while sz:
25                 sz -= 1
26                 node = q.popleft()
27                 t = max(t, node.val)
28                 if node.left:
29                     q.append(node.left)
30                 if node.right:
31                     q.append(node.right)
32             ans.append(t)
33         return ans

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