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
}
相关推荐
田梓燊4 分钟前
leetcode 240
算法·leetcode·职场和发展
We་ct13 分钟前
LeetCode 149. 直线上最多的点数:题解深度剖析
前端·javascript·算法·leetcode·typescript
sheeta199813 分钟前
LeetCode 每日一题笔记 日期:2026.04.13 题目:1848.到目标元素的最小距离
笔记·算法·leetcode
Tisfy20 分钟前
LeetCode 1848.到目标元素的最小距离:数组遍历(附python一行版)
python·leetcode·题解·遍历
XMYX-042 分钟前
08 - Go 函数(中):匿名函数、闭包与函数式编程
开发语言·golang
吃着火锅x唱着歌1 小时前
LeetCode 1963 使字符串平衡的最小交换次数
算法·leetcode·职场和发展
_日拱一卒1 小时前
LeetCode:螺旋矩阵
算法·leetcode·矩阵
呆萌很1 小时前
【GO】结构体组合练习题
golang
XMYX-01 小时前
07 - Go 函数(上):定义、参数、返回值与实战技巧
开发语言·后端·golang
Q741_1472 小时前
每日一题 力扣 1848. 到目标元素的最小距离 模拟 C++题解
c++·算法·leetcode·模拟