Path Sum I II III

来源:互联网 发布:dota2 a卡优化 编辑:程序博客网 时间:2024/05/22 08:23

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

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
原创粉丝点击