题号 112/113/437
pathsum III :https://www.jianshu.com/p/400586f0a7c9
import java.util.*;
public class PathSum {
/**
*
* pathSum:root --> leaf:看有没有加起来 == sum的路径
*
* dfs
* */
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null) {
return false;
}
if(root.left == null && root.right == null && sum == root.val) {
return true;
}
return hasPathSum(root.left, sum-root.val) || hasPathSum(root.right, sum-root.val);
}
/**
* pathSum ii:root --> leaf:返回所有 加起来 == sum的路径
*
* 回溯
* */
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> solution = new ArrayList<>();
findSum(res, solution, root, sum);
return res;
}
private void findSum(List<List<Integer>> result, List<Integer> solution, TreeNode root, int residual){
if (root == null) {
return;
}
residual -= root.val;
solution.add(root.val);
// 这里有必要解释下为什么不把这个条件和上一个条件合并
// 以 root==null,且 residual == root.val 作为终点;
// 因为这么写,左右子树会各来一遍,result会加入两遍solution
if (residual == 0 && root.left == null && root.right == null) {
result.add(new ArrayList<>(solution));
}
findSum(result, solution, root.left, residual);
findSum(result, solution, root.right, residual);
solution.remove(solution.size()-1);
}
/**
*
* pathSum iii:只要路径向下即可,不要求起终点为root和leaf:返回看加起来 == sum的路径的个数
*
* 前缀和
*/
public int pathSumIII(TreeNode root, int target) {
if(root == null) {
return 0;
}
Map<Integer, Integer> prefix = new HashMap<>();
prefix.put(0, 1);
return helper(root, target, prefix, 0);
}
private int helper(TreeNode root, int target, Map<Integer, Integer> prefix, int curSum) {
if(root == null) {
return 0;
}
int res = 0;
curSum += root.val;
// 此前存在路径的个数(A点 和 当前点 的差值是target,那么 A-当前点是有效路径)
res += prefix.getOrDefault(curSum-target, 0);
// 回溯
prefix.put(curSum, prefix.getOrDefault(curSum, 0) + 1);
res += helper(root.left, target, prefix, curSum);
res += helper(root.right, target, prefix, curSum);
prefix.put(curSum, prefix.getOrDefault(curSum, 0) - 1);
return res;
}
}