分成两种情况递归:路径包含当前结点,路径不包含当前结点。
/**
*
* 437. 路径总和 III
*
* 执行用时: 30 ms
* 内存消耗: 38.1 MB
*
*/
public class PathSumThree {
int ans = 0;
public int pathSum(TreeNode root, int targetSum) {
if(root == null){
return 0;
}
// 不算 root 在内的,左右可行的情况
pathSum(root.right, targetSum);
pathSum(root.left, targetSum);
// 算 root 在内的
bfs(root, targetSum, 0);
return ans;
}
void bfs(TreeNode root, int targetSum, int nowNum){
if(root == null){
return;
}
nowNum += root.val;
if(nowNum == targetSum){
ans++;
}
bfs(root.left, targetSum, nowNum);
bfs(root.right, targetSum, nowNum);
}
}