前缀和
class Solution {
HashMap < Integer , Integer > map;
public int pathSum ( TreeNode root, int targetSum) {
map= new HashMap < Integer , Integer > ( ) ;
map. put ( 0 , 1 ) ;
return dfs ( root, 0 , targetSum) ;
}
public int dfs ( TreeNode root, int cur, int targetSum) {
if ( root== null ) {
return 0 ;
}
cur+= root. val;
int ret= 0 ;
ret+= map. getOrDefault ( cur- targetSum, 0 ) ;
map. put ( cur, map. getOrDefault ( cur, 0 ) + 1 ) ;
ret+= dfs ( root. left, cur, targetSum) ;
ret+= dfs ( root. right, cur, targetSum) ;
map. put ( cur, map. getOrDefault ( cur, 0 ) - 1 ) ;
return ret;
}
}
递归
class Solution {
public int pathSum ( TreeNode root, int targetSum) {
if ( root== null ) return 0 ;
int ret= 0 ;
ret+= dfs ( root, targetSum) ;
ret+= pathSum ( root. left, targetSum) ;
ret+= pathSum ( root. right, targetSum) ;
return ret;
}
public int dfs ( TreeNode root, int targetSum) {
if ( root== null ) {
return 0 ;
}
int ret= 0 ;
if ( root. val== targetSum) {
ret++ ;
}
ret+= dfs ( root. left, targetSum- root. val) ;
ret+= dfs ( root. right, targetSum- root. val) ;
return ret;
}
}