剑指Offer专项突破版(50)—— 向下的路径节点之和

题目

剑指 Offer II 050. 向下的路径节点之和

在这里插入图片描述

思路

本题在树上使用前缀和思想

当遍历到某个节点n时,看以当前节点为路径的终点时,有多少个向下的路径和为target

假设从根到当前节点的路径和为sum,则看从根到当前节点之前的路径,有多少条和为

sum - target

例如上图中,10 -> 5 -> 2 -> 1 这条路径,从根10叶子节点1的sum为18,从根到根的sum为

sum - target = 10 ,因此找到一条路径和为8的路径,即5 -> 2 -> 1

代码

public int pathSum(TreeNode root, int targetSum) {
    HashMap<Long, Integer> map = new HashMap<>();
    map.put((long)0,1);
    return process(root,targetSum,0,map);
}

private int process(TreeNode root, int sum, long path, Map<Long,Integer> map) {
    if (root == null) {
        return 0;
    }

    path += root.val;
    // 看以root为结尾,有多少条路径的和为sum
    int count = map.getOrDefault(path - sum,0);
    if(!map.containsKey(path)) {
        map.put(path,1);
    } else {
        map.put(path,map.get(path) + 1);
    }

    count += process(root.left,sum,path,map);
    count += process(root.right,sum,path,map);

    map.put(path,map.get(path) - 1);
    return count;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值