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);
        }
    }
}
相关推荐
Dlrb12115 小时前
C语言-指针三
c语言·算法·指针·const·命令行参数
Tisfy5 小时前
LeetCode 2540.最小公共值:双指针(O(m+n))
算法·leetcode·题解·双指针
IronMurphy5 小时前
【算法四十七】152. 乘积最大子数组
算法
淘矿人6 小时前
Claude辅助DevOps实践
java·大数据·运维·人工智能·算法·bug·devops
Cosolar6 小时前
万字详解:RAG 向量索引算法与向量数据库架构及实战
数据库·人工智能·算法·数据库架构·milvus
落羽的落羽8 小时前
【算法札记】练习 | Week4
linux·服务器·数据结构·c++·人工智能·算法·动态规划
萑澈9 小时前
算法竞赛入门:C++ STL核心用法与时空复杂度速查手册
数据结构·c++·算法·stl
Godspeed Zhao9 小时前
从零开始学AI16——SVM
算法·机器学习·支持向量机
江屿风9 小时前
C++OJ题经验总结(竞赛)1
开发语言·c++·笔记·算法