1.题目
(1)题目1:给定一棵二叉树和一个和,确定树是否有根到叶的路径,这样沿路径加起来的所有值就等于给定的和。 例如: 鉴于下面的二叉树andsum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1 返回true,因为存在根到叶路径5→4→11→2,其和为22。 (2)题目2:给定一个二叉树和一个和,找到每个路径的总和等于给定总和的所有根到叶路径。 例如: 鉴于下面的二叉树andsum = 22, 5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1 返回: [ [5,4,11,2], [5,8,4,5] ]
2.分析过程
考察树的深度优先遍历DFS
3.代码实现
(1)代码1:
public class Solution{
public boolean hasPathSum(TreeNode root, int sum){
if(root==null) return false;
return hasPathSum1(root,sum);
}
public boolean hasPathSum1(TreeNode root, int sum){
if(root.left==null && root.right==null){
if(sum==root.val) return true;
else return false;
}else{
sum-=root.val;
if(root.left!=null && root.right!=null){
return hasPathSum1(root.left,sum) || hasPathSum1(root.right,sum);
}else{
if(root.left!=null) return hasPathSum1(root.left,sum);
else return hasPathSum1(root.right,sum);
}
}
}
}
(2)代码2:
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
ArrayList<ArrayList<Integer>> listAll=new ArrayList<>();
if(root==null) return listAll;
ArrayList<Integer> list=new ArrayList<>();
int count=0;
pathSum(root,sum,list,listAll,count);
return listAll;
}
public void pathSum(TreeNode root, int sum,ArrayList<Integer> list,ArrayList<ArrayList<Integer>> listAll,int count){
int temp=count;
ArrayList<Integer> tempList=new ArrayList<>();
tempList.addAll(list);
if(root.left==null && root.right==null){
temp+=root.val;
if(temp==sum){
tempList.add(root.val);
listAll.add(tempList);
}
}else{
temp+=root.val;
tempList.add(root.val);
if(root.left!=null) pathSum(root.left,sum,tempList,listAll,temp);
if(root.right!=null) pathSum(root.right,sum,tempList,listAll,temp);
}
}
}
题目1来自牛客网leetcode
题目2来自牛客网leetcode