1
/ \
3 2
/ \ \
5 3 9
Output: [1, 3, 9]
BFS的题目,我的做法:
def largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
res = []
self.helper(root,res,0)
return res
def helper(self,root,res,num):
if not root:
return None
if len(res) < num+1:
res.append(root.val)
else:
res[num] = max(res[num],root.val)
self.helper(root.left,res,num+1)
self.helper(root.right,res,num+1)```
别人的做法:
利用python中数组可以比较大小,运用map函数直接得出
```class Solution(object):
def largestValues(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if not root:
return []
res = []
left = self.largestValues(root.left)
right = self.largestValues(root.right)
return [root.val]+map(max,left,right)```
网友评论