【LeetCode热题100(47/100)】路径总和 III

题目地址: 链接

思路: 通过前缀和 + 回溯,每次记录当前前缀和,每次记录当前离 targetSum 的偏移量, 统计当前满足条件的路径数量。

js 复制代码
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @param {number} targetSum
 * @return {number}
 */
var pathSum = function(root, targetSum) {
    let map = new Map();
    let ans = 0;
    function dfs(root, pre) {
        if(!root) return null;
        
        let ppre = pre + root.val;
        let check_num = ppre - targetSum; // 偏移量

        ans += map.get(check_num) || 0;
        map.set(ppre, map.get(ppre) + 1 || 1);

        dfs(root.left, ppre);
        dfs(root.right,ppre);
        map.set(ppre, map.get(ppre) - 1);
    }
    map.set(0, 1);
    dfs(root, 0);
    return ans;
};
相关推荐
Tingjct11 分钟前
【初阶数据结构-二叉树】
c语言·开发语言·数据结构·算法
C雨后彩虹12 分钟前
计算疫情扩散时间
java·数据结构·算法·华为·面试
yyy(十一月限定版)1 小时前
寒假集训4——二分排序
算法
星火开发设计1 小时前
类型别名 typedef:让复杂类型更简洁
开发语言·c++·学习·算法·函数·知识
醉颜凉1 小时前
【LeetCode】打家劫舍III
c语言·算法·leetcode·树 深度优先搜索·动态规划 二叉树
达文汐1 小时前
【困难】力扣算法题解析LeetCode332:重新安排行程
java·数据结构·经验分享·算法·leetcode·力扣
一匹电信狗1 小时前
【LeetCode_21】合并两个有序链表
c语言·开发语言·数据结构·c++·算法·leetcode·stl
User_芊芊君子1 小时前
【LeetCode经典题解】搞定二叉树最近公共祖先:递归法+栈存路径法,附代码实现
算法·leetcode·职场和发展
培风图南以星河揽胜1 小时前
Java版LeetCode热题100之零钱兑换:动态规划经典问题深度解析
java·leetcode·动态规划
算法_小学生1 小时前
LeetCode 热题 100(分享最简单易懂的Python代码!)
python·算法·leetcode