Path Sum I II III

这三道题做了一下午,要继续努力。。。

Path Sum I:

public class Solution {
     public boolean hasPathSum(TreeNode root, int sum) {
        if(root==null)return false;
        if(sum-root.val==0 && root.left==null && root.right==null)return true;
        return hasPathSum(root.left,sum-root.val) || hasPathSum(root.right,sum-root.val);
    }
}


Path Sum II:

回溯法 

public class Solution {

public List<List<Integer>> pathSum(TreeNode root, int sum) {
       List<Integer> curList=new ArrayList<>();
       List< List<Integer>> res=new ArrayList<>();
       helper(root,curList,res,sum,0);
       return res;
    }
     
     public void helper(TreeNode root,List<Integer> curList,List<List<Integer>> res,int sum,int curVal){
    if(root==null){
    return;
    }
    curVal+=root.val;
    curList.add(root.val);
    if(root.left==null&&root.right==null&&curVal==sum){
    res.add(new ArrayList(curList));
    curList.remove(curList.size()-1);
    return;
    }
    else{
    helper(root.left,curList,res,sum,curVal);
    helper(root.right,curList,res,sum,curVal);
    }
    curList.remove(curList.size()-1);
     }

}

Path Sum III:

public class Solution {
    public int pathSum(TreeNode root, int sum) {
        if(root == null)
            return 0;
        return dfs(root, sum)+pathSum(root.left, sum)+pathSum(root.right, sum);
    }


    private int dfs(TreeNode root, int sum){
        int res = 0;
        if(root == null)
            return res;
        if(sum == root.val)
            res++;
        res+=dfs(root.left,sum - root.val);
        res+=dfs(root.right,sum - root.val);
        return res;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值