Golang | Leetcode Golang题解之第437题路径总和III

题目:

题解:

Go 复制代码
func pathSum(root *TreeNode, targetSum int) (ans int) {
    preSum := map[int64]int{0: 1}
    var dfs func(*TreeNode, int64)
    dfs = func(node *TreeNode, curr int64) {
        if node == nil {
            return
        }
        curr += int64(node.Val)
        ans += preSum[curr-int64(targetSum)]
        preSum[curr]++
        dfs(node.Left, curr)
        dfs(node.Right, curr)
        preSum[curr]--
        return
    }
    dfs(root, 0)
    return
}
相关推荐
AlenTech10 分钟前
141. 环形链表 - 力扣(LeetCode)
数据结构·leetcode·链表
dulu~dulu1 小时前
算法---寻找和为K的子数组
笔记·python·算法·leetcode
佑白雪乐2 小时前
<ACM进度212题>[2026-3-1,2026-3-26]
算法·leetcode
穿条秋裤到处跑2 小时前
每日一道leetcode(2026.03.26):等和矩阵分割 II
算法·leetcode·矩阵
x_xbx2 小时前
LeetCode:1. 两数之和
数据结构·算法·leetcode
x_xbx2 小时前
LeetCode:49. 字母异位词分组
算法·leetcode·职场和发展
老鼠只爱大米5 小时前
LeetCode经典算法面试题 #55:跳跃游戏(贪心法、动态规划、BFS等多种实现方案详解)
算法·leetcode·贪心算法·动态规划·bfs·java面试·跳跃游戏
旖-旎6 小时前
前缀和(矩阵区域和)(8)
c++·算法·leetcode·前缀和·动态规划
liuyao_xianhui6 小时前
优选算法_翻转链表_头插法_C++
开发语言·数据结构·c++·算法·leetcode·链表·动态规划
im_AMBER6 小时前
Leetcode 147 零钱兑换 | 单词拆分
javascript·学习·算法·leetcode·动态规划