【Hot100】LeetCode—437. 路径总和 III

目录

  • [1- 思路](#1- 思路)
  • [2- 实现](#2- 实现)
    • [⭐437. 路径总和 III------题解思路](#⭐437. 路径总和 III——题解思路)
  • [3- ACM 实现](#3- ACM 实现)


1- 思路

前缀和+哈希表+dfs

① 前缀和

  • 求二叉树的前缀和,每求一次用一个 sum 传参记录更新

② 哈希表

  • key 为前缀和 ,value 为出现频率
  • 用来记录前缀和出现的次数,原理就是如果 sum - targetSum 在前缀和的哈希中,则证明有目标和为 targetSum 的路径。出现次数就是该哈希出现的次数

③ dfs递归三部

  • 3.1 参数返回值,返回 void,参数为 sumroot
  • 3.2 终止条件,遇到 null 直接返回
  • 3.3 递归处理:递归求前缀和,如果哈希表存在sum - targetSum且出现次数大于等于 1 ,收集 res
    • 更新 sum
    • 递归 左节点
    • 递归 右结点
    • 回溯 更新 sum

2- 实现

⭐437. 路径总和 III------题解思路

java 复制代码
class Solution {
    int targetSum;
    int res = 0;
    HashMap<Long,Integer> hash = new HashMap<>();
    public int pathSum(TreeNode root, int targetSum) {
        this.targetSum = targetSum;
        hash.put(0L,1);
        dfs(0L,root);
        return res;
    }

    public void dfs(Long sum,TreeNode root){
        // 终止
        if(root==null){
            return;
        }
        // 递归
        sum+=root.val;
        if(hash.containsKey(sum-targetSum) && hash.get(sum-targetSum)>=1){
            res += hash.get(sum-targetSum);
        }
        hash.put((Long)sum,hash.getOrDefault(sum,0)+1);
        dfs(sum,root.left);
        dfs(sum,root.right);
        hash.put((Long)sum,hash.get(sum)-1);
    }
}

3- ACM 实现

java 复制代码
package Daily_LC.Month8_Week4.Day138;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

/**
 * pathSum
 *
 * @author alcohol
 * @Description
 * @since 2024-08-24 13:40
 */
public class pathSum {

    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode() {
        }

        TreeNode(int val) {
            this.val = val;
        }

        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }

    public static TreeNode build(String str) {
        if (str == null || str.length() == 0) {
            return null;
        }
        String input = str.replace("[", "");
        input = input.replace("]", "");
        String[] parts = input.split(",");

        Integer[] nums = new Integer[parts.length];
        for (int i = 0; i < parts.length; i++) {
            if (!parts[i].equals("null")) {
                nums[i] = Integer.parseInt(parts[i]);
            } else {
                nums[i] = null;
            }
        }
        Queue<TreeNode> queue = new LinkedList<>();
        TreeNode root = new TreeNode(nums[0]);
        queue.offer(root);
        int index = 1;
        while (!queue.isEmpty() && index < parts.length) {
            TreeNode node = queue.poll();
            if (index < nums.length && nums[index] != null) {
                node.left = new TreeNode(nums[index]);
                queue.offer(node.left);
            }
            index++;
            if (index < nums.length && nums[index] != null) {
                node.right = new TreeNode(nums[index]);
                queue.offer(node.right);
            }
            index++;
        }
        return root;
    }


    static int res = 0;
    static HashMap<Long, Integer> hash = new HashMap<>();

    public static int pathSum(TreeNode root, int targetSum) {

        hash.put(0L, 1);
        dfs(0L, root, targetSum);
        return res;
    }

    public static void dfs(Long sum, TreeNode root, int targetSum) {
        // 终止
        if (root == null) {
            return;
        }
        // 递归
        sum += root.val;
        if (hash.containsKey(sum - targetSum) && hash.get(sum - targetSum) >= 1) {
            res += hash.get(sum - targetSum);
        }
        hash.put((Long) sum, hash.getOrDefault(sum, 0) + 1);
        dfs(sum, root.left, targetSum);
        dfs(sum, root.right, targetSum);
        hash.put((Long) sum, hash.get(sum) - 1);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        String input = sc.nextLine();
        TreeNode root = build(input);
        System.out.println("输入目标和");
        int targetSum = sc.nextInt();
        pathSum(root, targetSum);
        System.out.println("结果是" + res);
    }

}
相关推荐
yidaqiqi15 分钟前
[目标检测] YOLO系列算法讲解
算法·yolo·目标检测
飞天狗11119 分钟前
2024 山东省ccpc省赛
c++·算法
卡尔曼的BD SLAMer31 分钟前
计算机视觉与深度学习 | Python实现EMD-SSA-VMD-LSTM-Attention时间序列预测(完整源码和数据)
python·深度学习·算法·cnn·lstm
珊瑚里的鱼1 小时前
【滑动窗口】LeetCode 1658题解 | 将 x 减到 0 的最小操作数
开发语言·c++·笔记·算法·leetcode·stl
落樱弥城1 小时前
角点特征:从传统算法到深度学习算法演进
人工智能·深度学习·算法
共享家95272 小时前
哈希的原理、实现
c++·算法
进击的小白菜2 小时前
用Java实现单词搜索(LeetCode 79)——回溯算法详解
java·算法·leetcode
珂朵莉MM2 小时前
2024 睿抗机器人开发者大赛CAIP-编程技能赛-专科组(国赛)解题报告 | 珂学家
开发语言·人工智能·算法·leetcode·职场和发展·深度优先·图论
小智学长 | 嵌入式2 小时前
进阶-数据结构部分:2、常用排序算法
java·数据结构·算法
少了一只鹅2 小时前
字符函数和字符串函数
c语言·算法