【leetcode】1302. Deepest Leaves Sum
题目如下:
Given a binary tree, return the sum of values of its deepest leaves.
Example 1:
Input: root = [1,2,3,4,5,null,6,7,null,null,null,null,8] Output: 15Constraints:
- The number of nodes in the tree is between
1
and10^4
.- The value of nodes is between
1
and100
.
解题思路:我的方法是做两次遍历,第一次求树的最大深度,第二次求和。
代码如下:
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): level = 0 leavesSum = 0 def getMaxLevel(self,node,level): self.level = max(self.level,level) if node == None: return if node.left != None: self.getMaxLevel(node.left,level + 1) if node.right != None: self.getMaxLevel(node.right,level + 1) def calc(self,node,level): if level == self.level: self.leavesSum += node.val if node == None: return if node.left != None: self.calc(node.left,level + 1) if node.right != None: self.calc(node.right,level + 1) def deepestLeavesSum(self, root): """ :type root: TreeNode :rtype: int """ self.leavesSum = 0 self.level = 0 self.getMaxLevel(root,0) self.calc(root,0) return self.leavesSum