问题:node
You are given a binary tree in which each node contains an integer value.spa
Find the number of paths that sum to a given value.get
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).it
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.io
Example:class
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 10 / \ 5 -3 / \ \ 3 2 11 / \ \ 3 -2 1 Return 3. The paths that sum to 8 are: 1. 5 -> 3 2. 5 -> 2 -> 1 3. -3 -> 11
解决:二叉树
① 这道题就是给了一个二叉树和一个目标和sum,找出全部路径,这个路径的和等于sum,只容许从父节点到子节点的路线。使用DFS(Dpeth-first Search,深度优先搜索)查找知足条件的路径。搜索
/** *遍历
Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {//30ms
public int pathSum(TreeNode root, int sum) {
if(root == null) //必须判断,不然会越界
return 0;
return dfs(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum);
}
private int dfs(TreeNode root, int sum){
int count = 0;
if(root == null)
return count;
if(sum == root.val)
count ++;
count += dfs(root.left,sum - root.val);
count += dfs(root.right,sum - root.val);
return count;
}
}map
② 用map记录当前遍历路径中的子路径权值和对应出现的次数。
1. sum表示从根节点到某节点X,路径的权值和,则遍历至X节点时,当前的路径和curSum刚好与sum相等,此时count = map.getOrDefault(curSum - target,0) = map.get(0) = 1;
2. 若sum为某段子路径的权值和,如:x1->x2->x3->x4......中sum等于节点x3与节点x4的权值和,即sum = sum(x3+x4)。则遍历至x2时, m[curSum]++; 处已经记录了m[curSum] = m[sum(x1+x2)] = 1,遍历至x4时curSum = sum(x1+x2+x3+x4),则res = m[curSum - sum] = m[sum(x1+x2+x3+x4) - sum(x3+x4)] = m[sum(x1+x2)] = 1。
public class Solution {//26ms public int pathSum(TreeNode root, int sum) { Map<Integer,Integer> map = new HashMap<Integer,Integer>();//map(curSum,个数) map.put(0,1);//初始权值为0,个数为1 return dfs(root,sum,map,0); } public int dfs(TreeNode root,int sum,Map<Integer,Integer> map,int curSum){ if(root == null) return 0; curSum += root.val; int count = map.getOrDefault(curSum - sum,0);//获取当前子节点包含权值为 sum的子段的个数 map.put(curSum,map.getOrDefault(curSum,0) + 1);//记录当前子节点权值的个数加1 count += dfs(root.left,sum,map,curSum) + dfs(root.right,sum,map,curSum); map.put(curSum,map.get(curSum) - 1); return count; } }