import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @param sum int整型
* @return int整型ArrayList<ArrayList<>>
*/
public ArrayList<ArrayList<Integer>> pathSum (TreeNode root, int sum) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
ArrayList<Integer> list = new ArrayList<>();
preTree(root, sum, list, result);
return result;
}
public void preTree(TreeNode root, int sum, ArrayList<Integer> list, ArrayList<ArrayList<Integer>> result){
if (root == null) {
return;
}
/**
* 这里为什么不能这样写:
* 如果树中的每个节点都是正整数 那没有问题
* 如果树中都是是负数或者有负有正 那就有问题了
*/
// if ((sum - root.val) < 0) {
// return;
// }
if (root.left == null && root.right == null && (sum - root.val) == 0) {
list.add(root.val);
result.add(new ArrayList(list));
list.remove(list.size()-1);
return;
}
list.add(root.val);
preTree(root.left, sum - root.val, list, result);
preTree(root.right, sum - root.val, list, result);
list.remove(list.size()-1);
}
}