Description

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: 15

Constraints:

  • The number of nodes in the tree is between 1 and 10^4.
  • The value of nodes is between 1 and 100.

分析

题目的意思是:求出二叉树最深的叶子结点的和,我的办法挺笨的,首先递归找到最大深度,然后再遍历求出最大深度的叶子结点。我看了另一种思路是用一个全局变量来存储最大深度d,用sum存储叶子结点的和,当当前的深度depth>d时,更新d,然后sum置0.当depth==d时,sum要加上当前的值,然后进行递归,思路比我好,哈哈。

代码

# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def getDepth(self,root,depth):
if(root is None):
return
self.getDepth(root.left,depth+1)
self.getDepth(root.right,depth+1)
self.maxDepth=max(self.maxDepth,depth)

def solve(self,root,depth):
if(root is None):
return 0
l=self.solve(root.left,depth+1)
r=self.solve(root.right,depth+1)
if(root.left is None and root.right is None and depth==self.maxDepth):
return root.val
return l+r

def deepestLeavesSum(self, root: TreeNode) -> int:
self.maxDepth=0
self.getDepth(root,0)
res=self.solve(root,0)
return res

参考文献

​[LeetCode] [Java] Recursive, faster than 100.00%​