【leetcode】113. 路径总和 II(Java)

题目描述

题目链接113. 路径总和 II
【leetcode】113. 路径总和 II(Java)_第1张图片

题解

经典回溯。

  • 终止条件: 当遍历到叶子节点,并且此时路径的值 == targerSum,此时收集当前的path。
  • 处理逻辑:我们遍历到一个节点时,可以把targetSum - root.val作为下一层的targetSum,所以当我们找到叶子节点的时候,并且root.val == targetSum,就可以收集了。

完整代码

class Solution {
    List<List<Integer>> res = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
        dfs(root, targetSum);
        return res;
    }

    public void dfs(TreeNode root, int targetSum){
        if (root == null) return;
        path.add(root.val);
        if (root.left == null && root.right == null && targetSum == root.val){
            res.add(new ArrayList(path));
        }
        dfs(root.left, targetSum - root.val);
        dfs(root.right, targetSum - root.val);
        path.remove(path.size() - 1);
    }
}

你可能感兴趣的:(Leetcode,leetcode,java,算法)