leetcode133_路径总和II

题目链接:https://leetcode-cn.com/problems/path-sum-ii/submissions/
这道题需要对整个树进行遍历,对结果的存储可以用参数解决,所以不需要返回值。

class Solution {
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        List<List<Integer>> result = new ArrayList();
        if(root == null) return result;
        List<Integer> path = new ArrayList();
        dfs(root, path, result, targetSum);
        return result;
    }
    private void dfs(TreeNode root, List<Integer> path, List<List<Integer>> result, int targetSum) {
        path.add(root.val);
        if(root.left == null && root.right == null) {
            Integer sum = path.stream().mapToInt(Integer::intValue).sum();
            if(targetSum == sum) result.add(new ArrayList<>(path));
        }
        if(root.left != null) {
            dfs(root.left, path, result, targetSum);
            path.remove(path.size()-1);
        }
        if(root.right != null) {
            dfs(root.right, path, result, targetSum);
            path.remove(path.size()-1);
        }
    }
}

但是依然存在几个问题:

  1. result.add(new ArrayList<>(path)); 而不是result.add(path);
  2. 忽略了"path.add(root.val)"
  3. 应该使用减法
  4. 对一个List的求和
Iteger sum = path.stream().mapToInt(Integer::intValue).sum()
posted @ 2022-03-06 13:40  明卿册  阅读(28)  评论(0)    收藏  举报