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);
        }
    }
}
相关推荐
沙蒿同学20 分钟前
当古诗词遇上 AI:从 38 万句诗词中取一个好名字
python·算法·架构
变量未定义~32 分钟前
单调栈、单调队列(模板)、子矩阵(模板)
数据结构·算法·蓝桥杯
不会就选b42 分钟前
算法日常・每日刷题--<快速排序>2
数据结构·算法
CClaris1 小时前
大模型量化从0到1(五):GPTQ 原理详解 + 从零量化一个真实大模型
人工智能·python·算法·机器学习
凯瑟琳.奥古斯特1 小时前
力扣1012数位DP解法详解
开发语言·c++·算法·leetcode·职场和发展
大鱼>1 小时前
AI+货物追踪:贵重物品智能追踪系统
人工智能·深度学习·算法·机器学习
大鱼>2 小时前
AI+货物追踪:集装箱智能追踪系统
人工智能·深度学习·算法·机器学习
z小猫不吃鱼2 小时前
模型剪枝经典论文精读:NISP: Pruning Networks using Neuron Importance Score Propagation
算法·机器学习·剪枝
researcher-Jiang2 小时前
栈的模板类与基本应用(还差栈混洗)
算法
foundbug9993 小时前
Polar Code 编解码 MATLAB 实现
开发语言·算法·matlab