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);
        }
    }
}
相关推荐
SirLancelot19 分钟前
数据结构-Set集合(一)Set集合介绍、优缺点
java·开发语言·数据结构·后端·算法·哈希算法·set
YouQian77218 分钟前
label 拓扑排序
数据结构·算法
YouQian77219 分钟前
(补题)小塔的饭
算法
歌者長門20 分钟前
做题笔记:某大讯飞真题28道
java·数据结构·算法
是店小二呀1 小时前
【动态规划 | 多状态问题】动态规划求解多状态问题
算法·动态规划
竹子_231 小时前
《零基础入门AI:传统机器学习核心算法解析(KNN、模型调优与朴素贝叶斯)》
人工智能·算法·机器学习
boyedu1 小时前
哈希指针与数据结构:构建可信数字世界的基石
数据结构·算法·区块链·哈希算法·加密货币
✿ ༺ ོIT技术༻2 小时前
剑指offer第2版:双指针+排序+分治+滑动窗口
算法·排序算法·剑指offer·双指针·滑动窗口·分治
细嗅蔷薇@2 小时前
C语言在键盘上输入一个3行3列矩阵的各个元素的值(值为整数),然后输出主对角线元素的积,并在fun()函数中输出。
c语言·算法·矩阵
新时代苦力工3 小时前
桶排序-Java实现
数据结构·算法·排序算法