//递归
public boolean hasPathSum(TreeNode root, int sum) {
if(root == null)return false;
if(root.left == null && root.right ==null)return sum == root.val;
return hasPathSum(root.left , sum - root.val) || hasPathSum(root.right , sum - root.val);
}
路径总和 2
//动态规划
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> res = new ArrayList<>();
pathSums(root,ans , res , sum);
return ans;
}
public void pathSums(TreeNode root,List<List<Integer>> ans , List<Integer> res , int sum)
{
if(root == null)return;
if(root.left == null && root.right == null)//到达叶节点
{
if(sum == root.val)
{
res.add(root.val);
ans.add(new ArrayList<>(res));
res.remove(res.size()-1);
return;
}
}
res.add(root.val);
pathSums(root.left , ans , res , sum - root.val);
pathSums(root.right , ans ,res ,sum - root.val);
res.remove(res.size()-1);
}