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);
        }
    }
}
相关推荐
涛ing2 小时前
32. C 语言 安全函数( _s 尾缀)
linux·c语言·c++·vscode·算法·安全·vim
独正己身3 小时前
代码随想录day4
数据结构·c++·算法
利刃大大6 小时前
【回溯+剪枝】找出所有子集的异或总和再求和 && 全排列Ⅱ
c++·算法·深度优先·剪枝
Rachela_z7 小时前
代码随想录算法训练营第十四天| 二叉树2
数据结构·算法
细嗅蔷薇@7 小时前
迪杰斯特拉(Dijkstra)算法
数据结构·算法
追求源于热爱!7 小时前
记5(一元逻辑回归+线性分类器+多元逻辑回归
算法·机器学习·逻辑回归
ElseWhereR7 小时前
C++ 写一个简单的加减法计算器
开发语言·c++·算法
Smark.7 小时前
Gurobi基础语法之 addConstr, addConstrs, addQConstr, addMQConstr
算法
S-X-S7 小时前
算法总结-数组/字符串
java·数据结构·算法
Joyner20188 小时前
python-leetcode-从中序与后序遍历序列构造二叉树
算法·leetcode·职场和发展