给定一棵二叉树,其中每个节点都含有一个整数数值(该值或正或负)。设计一个算法,打印节点数值总和等于某个给定值的所有路径的数量。注意,路径不一定非得从二叉树的根节点或叶节点开始或结束,但是其方向必须向下(只能从父节点指向子节点方向)。
示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
3
解释:和为 22 的路径有:[5,4,11,2], [5,8,4,5], [4,11,7]
代码
class Solution {
int tar, cnt = 0;
public int pathSum(TreeNode root, int sum) {
tar = sum;
Sum(root, 0, new LinkedList<>());
return cnt;
}
public void Sum(TreeNode root, int sum, LinkedList<Integer> res) {
if (root == null) return;
res.add(root.val);
cnt += um(res);
Sum(root.left, sum + root.val, res);
Sum(root.right, sum + root.val, res);
res.removeLast();
}
public int um(LinkedList<Integer> res) {
int temp = 0, r = 0;
for (int i = res.size() - 1; i >= 0; i--) {
r += res.get(i);
if (r == tar) temp++;
}
return temp;
}
}
递归+前缀和+回溯代码
class Solution {
int tar;
public int pathSum(TreeNode root, int sum) {
tar = sum;
HashMap<Integer,Integer> map=new HashMap<>();
map.put(0,1);
return helper(root, 0,map);
}
public int helper(TreeNode root, int sum, HashMap<Integer,Integer> map) {
if (root == null) return 0;
int cnt=0;
int res=sum+root.val;
cnt +=map.getOrDefault(res-tar,0);
map.put(res,map.getOrDefault(res,0)+1);
if(root.left!=null) cnt+=helper(root.left, res, map);
if(root.right!=null) cnt+=helper(root.right, res, map);
map.put(res,map.get(res)-1);
return cnt;
}
}