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 分钟前
【算法训练营 · 补充】LeetCode Hot100(中)
算法·leetcode
橘颂TA22 分钟前
【剑斩OFFER】算法的暴力美学——最小覆盖字串
算法·c/c++·就业
wearegogog12324 分钟前
基于混合蛙跳算法和漏桶算法的无线传感器网络拥塞控制与分簇新方法
网络·算法
Tiandaren1 小时前
大模型应用03 || 函数调用 Function Calling || 概念、思想、流程
人工智能·算法·microsoft·数据分析
2301_795167202 小时前
玩转Rust高级应用 如何进行理解Refutability(可反驳性): 模式是否会匹配失效
开发语言·算法·rust
小当家.1052 小时前
[LeetCode]Hot100系列.贪心总结+思想总结
算法·leetcode·职场和发展
墨雪不会编程3 小时前
数据结构—排序算法篇二
数据结构·算法·排序算法
ShineWinsu3 小时前
对于数据结构:堆的超详细保姆级解析—上
数据结构·c++·算法·计算机·二叉树·顺序表·
im_AMBER3 小时前
Leetcode 46
c语言·c++·笔记·学习·算法·leetcode
努力学算法的蒟蒻4 小时前
day09(11.6)——leetcode面试经典150
算法·leetcode·职场和发展