//递归法
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root==null) return false;
return find(root,targetSum-root.val);
}public boolean find(TreeNode root,int targetSum){
if(root.left==null&&root.right==null&&targetSum==0) return true;
if(root.left==null&&root.right==null) return false;
if(root.left!=null){
targetSum-=root.left.val;
if(find(root.left,targetSum)) return true;
targetSum+=root.left.val;
}
if(root.right!=null){
targetSum-=root.right.val;
if(find(root.right,targetSum)) return true;
targetSum+=root.right.val;
}
return false;
}
}
//迭代法
class Solution {
public boolean hasPathSum(TreeNode root, int targetSum) {
if(root==null) return false;
Stack stack1=new Stack<>();
Stack satck2=new Stack<>();
stack1.push(root);
satck2.push(root.val);
while(!stack1.isEmpty()){
int size=stack1.size();
for(int i=0;i