LeetCode知识点总结 - 437

该博客详细介绍了如何解决LeetCode中的437题,即寻找二叉树中和为目标值的路径数量。博主通过深度优先搜索(DFS)策略,利用全局变量记录结果,并使用字典缓存中间结果,实现了从根节点到任意节点的路径和。在离开路径时,博主清除了当前路径和,以避免重复计数。最后返回结果。此题属于中等难度,主要考察了二叉树遍历和动态规划的知识。
摘要由CSDN通过智能技术生成

LeetCode 437. Path Sum III

考点难度
DFSMedium
题目

Given the root of a binary tree and an integer targetSum, return the number of paths where the sum of the values along the path equals targetSum.

The path does not need to start or end at the root or a leaf, but it must go downwards (i.e., traveling only from parent nodes to child nodes).

思路

对每个node, 如果从root到node的所有和为currentsum, 如果这条path上有满足条件的说明有oldsum = currentsum - target, 所以只需要数oldsum出现的次数。
离开path之前需要清空cache。

答案
class Solution(object):
    def pathSum(self, root, target):
        # define global result and path
        self.result = 0
        cache = {0:1}
        
        # recursive to get result
        self.dfs(root, target, 0, cache)
        
        # return result
        return self.result
    
    def dfs(self, root, target, currPathSum, cache):
        # exit condition
        if root is None:
            return  
        # calculate currPathSum and required oldPathSum
        currPathSum += root.val
        oldPathSum = currPathSum - target
        # update result and cache
        self.result += cache.get(oldPathSum, 0)
        cache[currPathSum] = cache.get(currPathSum, 0) + 1
        
        # dfs breakdown
        self.dfs(root.left, target, currPathSum, cache)
        self.dfs(root.right, target, currPathSum, cache)
        # when move to a different branch, the currPathSum is no longer available, hence remove one. 
        cache[currPathSum] -= 1
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值