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
}
相关推荐
名字还没想好☜5 小时前
Go context.AfterFunc 实战(Go 1.21):context 一取消就自动跑清理,告别手写 goroutine 监听 Done
后端·golang·go
web守墓人5 小时前
【goed/ui】自定义组件设计思想篇
linux·windows·ui·golang
午彦琳9 小时前
2026.9.17
数据结构·算法·leetcode
木井巳9 小时前
【记忆化搜索】不同路径
java·算法·leetcode·深度优先·剪枝·推荐算法
All for pursuit.12 小时前
【链表-9】146.LRU缓存
数据结构·c++·算法·leetcode
圣保罗的大教堂12 小时前
leetcode 1477. 找两个和为目标值且不重叠的子数组 中等
leetcode
hanlin0313 小时前
刷题笔记:力扣第144题-二叉树的前序遍历
笔记·算法·leetcode
圣保罗的大教堂15 小时前
leetcode 3629. 通过质数传送到达终点的最少跳跃次数 中等
leetcode
圣保罗的大教堂15 小时前
leetcode 1914. 循环轮转矩阵 中等
leetcode
wabs66616 小时前
关于二叉树【力扣100.相同的树的思考】
数据结构·c++·算法·leetcode·二叉树·递归法