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
}
相关推荐
leonkay3 分钟前
Golang语言闭包完全指南
开发语言·数据结构·后端·算法·架构·golang
IronMurphy3 小时前
【算法二十六】108. 将有序数组转换为二叉搜索树 98. 验证二叉搜索树
数据结构·算法·leetcode
im_AMBER3 小时前
Leetcode 141 最长公共前缀 | 罗马数字转整数
算法·leetcode
WolfGang0073214 小时前
代码随想录算法训练营 Day13 | 二叉树 part03
数据结构·算法·leetcode
一叶落4385 小时前
167. 两数之和 II - 输入有序数组【C语言题解】
c语言·数据结构·算法·leetcode
echome8885 小时前
Go 语言并发编程实战:用 Goroutine 和 Channel 构建高性能任务调度器
开发语言·后端·golang
一叶落4386 小时前
LeetCode 54. 螺旋矩阵(C语言详解)——模拟 + 四边界收缩
java·c语言·数据结构·算法·leetcode·矩阵
王老师青少年编程6 小时前
2026年3月GESP真题及题解(C++二级):数数
c++·题解·真题·gesp·数数·二级·2026年3月
Storynone6 小时前
【Day27】LeetCode:56. 合并区间,738. 单调递增的数字
python·算法·leetcode
计算机安禾7 小时前
【C语言程序设计】第31篇:指针与函数
c语言·开发语言·数据结构·c++·算法·leetcode·visual studio