简单的递归,通过参数回溯
class Solution {
boolean isSum=false;
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root==null) return false;
traversal(root,targetSum,0);
return isSum;
}
public void traversal(TreeNode root,int target,int sum){
if(root.left==null&&root.right==null){
if(sum+root.val==target) isSum=true;
return;
}
if(root.left!=null) traversal(root.left,target,sum+root.val);//此处有回溯
if(root.right!=null) traversal(root.right,target,sum+root.val);//此处有回溯
}
}