路径总和-
https://leetcode.cn/problems/path-sum/
判断是否有从根结点到叶子结点的路径值(val)总和为targetSum的路径,有返回true or false
1Solution <递归> Accepted / Used 时空复杂度 O(n) O(n)
class Solution {
static boolean f(TreeNode root,int tsum,int sum) {
if(root.left==null&&root.right==null) {
return tsum==sum;
}
boolean b = false;
if(root.left!=null) b = f(root.left,tsum,sum+root.left.val);
if((!b)&&root.right!=null) b = f(root.right,tsum,sum+root.right.val);
return b;
}
public boolean hasPathSum(TreeNode root, int tsum) {
if(root==null) return false;
return f(root,tsum,root.val);
}
}