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);
        }
    }
}
相关推荐
艾醒12 小时前
打破信息差——2026年2月19日AI热点新闻速览
算法
追随者永远是胜利者14 小时前
(LeetCode-Hot100)62. 不同路径
java·算法·leetcode·职场和发展·go
追随者永远是胜利者14 小时前
(LeetCode-Hot100)56. 合并区间
java·算法·leetcode·职场和发展·go
wu_asia14 小时前
每日一练伍
算法
追随者永远是胜利者14 小时前
(LeetCode-Hot100)55. 跳跃游戏
java·算法·leetcode·游戏·go
近津薪荼14 小时前
优选算法——前缀和(7):连续数组
算法
ArturiaZ15 小时前
【day29】
数据结构·c++·算法
MoonOutCloudBack15 小时前
VeRL 框架下 RL 微调 DeepSeek-7B,比较 PPO / GRPO 脚本的参数差异
人工智能·深度学习·算法·语言模型·自然语言处理
_F_y15 小时前
二叉树中的深搜
算法
锅包一切15 小时前
PART17 一维动态规划
c++·学习·算法·leetcode·动态规划·力扣·刷题