import java.util.*;
import java.util.ArrayList;
/*
* 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) {
// write code here
ArrayList <ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> path=new ArrayList<Integer>();
if(root==null)return res;
path.add(root.val);
dfs(root,sum,path,res);
return res;
}
public static void dfs(TreeNode root,int sum,ArrayList path,ArrayList <ArrayList<Integer>> res){
if (root.left==null&&root.right==null &&sum(path)==sum){
res.add(new ArrayList<>(path));
}
if (root.left!=null){
path.add(root.left.val);
dfs(root.left,sum,path,res);
path.remove(path.size()-1);//此处注意,和Python不同,需要自行移除
}
if (root.right!=null){
path.add(root.right.val);
dfs(root.right,sum,path,res);
path.remove(path.size()-1);
}
}
public static int sum(ArrayList list){//自己写一个求和函数
int s=0;
for(Object i:list){
s+=(int)i;
}
return s;
}
}