一:题目
二:上码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
private List<List<Integer>> ans = new ArrayList<>();
private List<Integer> path = new ArrayList<>();
public int getSum(List<Integer> list) {
int sum = 0;
for (int i = 0; i < list.size(); i++) {
sum += list.get(i);
}
return sum;
}
public void preOrder(TreeNode root,int targetSum) {
if (root == null) return ;
if (root.left == null && root.right == null) {
int nums = getSum(path);
if (nums == targetSum) {
ans.add(new ArrayList<>(path));//这里是不可以直接添加path的
}
}
if (root.left != null) {//这里添加root.left的判空主要就是未来下方的 root.left.val ;
path.add(root.left.val);
preOrder(root.left,targetSum);
path.remove(path.size()-1);
}
if (root.right != null) {
path.add(root.right.val);
preOrder(root.right,targetSum);
path.remove(path.size()-1);
}
return;
}
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
if (root != null) path.add(root.val);
preOrder(root,targetSum);
return ans;
}
}