https://leetcode.com/problems/path-sum-iii/
找出以任意节点为起点的和为sum的路径个数
解法一:
递归,时间复杂度O(NlogN),两个函数:一个是包含当前节点的合法路径总数,另一个是不包含当前节点的
public class Solution {
public int pathSum(TreeNode root, int sum) {
if (root == null) {
return 0;
}
return pathSum(root.left, sum) + pathSum(root.right, sum) + findSum(root, sum);
}
private int findSum(TreeNode root, int sum) {
int res = 0;
if (root == null) {
return res;
}
if (root.val == sum) {
res++;
}
res = res + findSum(root.left, sum - root.val) + findSum(root.right, sum - root.val);
return res;
}
}
解法二:
public class Solution {
public int pathSum(TreeNode root, int sum) {
// 保存从根节点到当前节点之间的节点与根节点的和以及这些和的个数
HashMap<Integer, Integer> map = new HashMap();
map.put(0, 1);
return backTrace(root, 0, sum, map);
}
private int backTrace(TreeNode root, int cur, int target, HashMap<Integer, Integer> map) {
if (root == null) {
return 0;
}
cur += root.val;
// 当前
int res = map.getOrDefault(cur - target, 0);
map.put(cur, map.getOrDefault(cur, 0) + 1);
res = res + backTrace(root.left, cur, target, map) + backTrace(root.right, cur, target, map);
map.put(cur, map.get(cur) - 1);
return res;
}
}