[leetcode] 1302. Deepest Leaves Sum

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%

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值