路径总和 II——leetcode113

路径总和 II

题目:路径总和 II

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

示例 1:

输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:[[5,4,11,2],[5,8,4,5]]

题解

class Solution {
    private List<List<Integer>> res;

    public void dfs(TreeNode root, int sum, int target, List<Integer> level)
    {
        if(root==null) return;
        sum+=root.val;
        level.add(root.val);
        if(root.left==null&&root.right==null)
        {
            if(sum==target)
            {
                res.add(new ArrayList<>(level));
            }
            level.remove(level.size()-1);
            return;
        }
        dfs(root.left, sum, target, level);
        dfs(root.right, sum, target, level);
        level.remove(level.size()-1);
    }
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        res=new ArrayList<>();
        List<Integer> level=new ArrayList<>();
        dfs(root, 0, targetSum,level);

        return res;
    }
}

 

posted @ 2021-12-31 12:26  言思宁  阅读(26)  评论(0编辑  收藏  举报