对于根结点来说,可以选择当前结点为路径也可以不选择,但是一旦选择当前结点为路径那么后续都必须要选择结点作为路径,不然路径不连续是不合法的,所以这里分开出来两个方法进行递归
由于力扣最后一个用例解答错误,分析发现targetSum减法多次后可能越界之类的情况把参数类型改为了long
/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public int pathSum(TreeNode root, long targetSum) {if (root == null) {return 0;} else {if (targetSum - root.val == 0) {return 1+ getSum(root.left, targetSum - root.val)+ getSum(root.right, targetSum - root.val)+ pathSum(root.left, targetSum)+ pathSum(root.right, targetSum);} else {return getSum(root.left, targetSum - root.val)+ getSum(root.right, targetSum - root.val)+ pathSum(root.left, targetSum)+ pathSum(root.right, targetSum);}}}private int getSum(TreeNode root, long targetSum) {if (root == null) {return 0;} else {targetSum-=root.val;if (targetSum == 0) {return 1 + getSum(root.left, targetSum) + getSum(root.right, targetSum);} else {return getSum(root.left, targetSum) + getSum(root.right, targetSum);}}}
}