Leetcode113. 路径总和 II

力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

官方题解:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

代码如下:

java 复制代码
class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> res = new ArrayList<>();
        if(root == null) {
            return res;
        }
        List<Integer> path = new ArrayList<>();
        path.add(root.val);
        targetSum -= root.val;
        dfs(root,targetSum,path,res);
        return res;

    }
    public void dfs(TreeNode root,int sum,List<Integer> path,List<List<Integer>> res){
        if(root.left == null && root.right == null && sum == 0){
            res.add(new ArrayList<>(path));
            return;
        }
       
        if(root.left != null) {
            path.add(root.left.val); 
            sum -= root.left.val;
            dfs(root.left,sum,path,res);
            sum += root.left.val;
            path.remove(path.size()-1);
        }
       
        if(root.right != null) {
            path.add(root.right.val); 
            sum -= root.right.val;
            dfs(root.right,sum,path,res);
            sum += root.right.val;
            path.remove(path.size()-1);
        }
    }
}
相关推荐
GUIQU.12 分钟前
【每日一题 | 2025年5.5 ~ 5.11】搜索相关题
算法·每日一题·坚持
不知名小菜鸡.13 分钟前
记录算法笔记(2025.5.13)二叉树的最大深度
笔记·算法
小雅痞14 分钟前
[Java][Leetcode middle] 55. 跳跃游戏
java·leetcode
真的想上岸啊42 分钟前
c语言第一个小游戏:贪吃蛇小游戏05
c语言·算法·链表
元亓亓亓1 小时前
LeetCode热题100--206.反转链表--简单
算法·leetcode·链表
边跑边掩护1 小时前
LeetCode 373 查找和最小的 K 对数字题解
leetcode
诚丞成1 小时前
BFS算法篇——从晨曦到星辰,BFS算法在多源最短路径问题中的诗意航行(上)
java·算法·宽度优先
hongjianMa1 小时前
2024睿抗编程赛国赛-题解
算法·深度优先·图论·caip
czy87874752 小时前
两种常见的C语言实现64位无符号整数乘以64位无符号整数的实现方法
c语言·算法
yzx9910132 小时前
支持向量机案例
算法·机器学习·支持向量机