Featured image of post LeetCode113.路径总合II

LeetCode113.路径总合II

LeetCode113.路径总合II

题目:

image-20250409215254161image-20250409215307157

答案:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
    static List<List<Integer>> ans;
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        if (root == null) return ans;
        ans=new ArrayList<>();
        dfs(new ArrayList<>(),root,0,targetSum);
        return ans;
    }

    public static void dfs(List<Integer> list,TreeNode node,int sum,int targetSum){
        if (node==null){
            return;
        }
        list.add(node.val);
        sum += node.val;
        
        if (node.left == null && node.right == null && sum == targetSum) {
            ans.add(new ArrayList<>(list)); // 这里一定要 new 一个副本
        }

        dfs(list,node.left,sum,targetSum);
        dfs(list,node.right,sum,targetSum);
        list.remove(list.size()-1);
    }
}
NovaBryan的博客
使用 Hugo 构建
主题 StackJimmy 设计