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);
        }
    }
}
相关推荐
hetao173383719 分钟前
2026-09-29 hetao1733837 的刷题记录
c++·算法
欣欣之王来了1 小时前
AI合规专项:AI算法透明度的合规要求
人工智能·算法
wzdark1 小时前
分块思想在算法优化中的实践与应用4
算法
Because_of_Her11 小时前
dfs-洪水填充技巧
笔记·算法·深度优先·洪水填充
小静AI工程实验室1 小时前
RSA 算法详解:从模幂原理到 OAEP 加密、PSS 签名与 Python 实验
python·算法
xzal122 小时前
GESP Python笔记
笔记·python·算法
wzdark2 小时前
算法中的记忆化思想与重复子问题优化4
算法
Discipline10292 小时前
流水线运行是否正随时间变得更加集中?
算法
lzhdim2 小时前
C#不为人知的10个魔法特性:资深开发者也会震惊的底层奥秘
java·前端·javascript·算法·c#
weixin_307779132 小时前
C++代码实现MATLAB中的pade函数功能
开发语言·c++·算法·matlab