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
}
相关推荐
添尹38 分钟前
Go语言基础之变量和常量
golang
灰色小旋风2 小时前
力扣13 罗马数字转整数
数据结构·c++·算法·leetcode
阿里嘎多哈基米5 小时前
速通Hot100-Day09——二叉树
算法·leetcode·二叉树·hot100
Frostnova丶5 小时前
LeetCode 48 & 1886.矩阵旋转与判断
算法·leetcode·矩阵
多打代码5 小时前
2026.3.22 回文子串
算法·leetcode·职场和发展
im_AMBER5 小时前
Leetcode 144 位1的个数 | 只出现一次的数字
学习·算法·leetcode
小刘不想改BUG5 小时前
LeetCode 138.随机链表的复制 Java
java·leetcode·链表·hash table
参.商.6 小时前
【Day43】49. 字母异位词分组
leetcode·golang
参.商.6 小时前
【Day45】647. 回文子串 5. 最长回文子串
leetcode·golang
Trouvaille ~6 小时前
【优选算法篇】哈希表——空间换时间的极致艺术
c++·算法·leetcode·青少年编程·蓝桥杯·哈希算法·散列表