递归遍历记录当前的总数以及路径。当遍历到根节点(左右子树都为空时),就看当前总数是否与sum相等,相等就把当前的路径加到结果集里。

import java.util.*;

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<>();
        getRes(root,sum,res,0,new Stack<Integer>());
        return res;
    }
    public void getRes(TreeNode root, int sum ,ArrayList<ArrayList<Integer>> res, int curr, Stack<Integer> currNums){
        if(null==root)
            return;
        if(null == root.left && null == root.right){
            curr+=root.val;
            currNums.push(root.val);
            if(sum==curr){
                if(!currNums.isEmpty()){
                    ArrayList<Integer> list = new ArrayList(Arrays.asList(currNums.toArray(new Integer[0])));
                    res.add(list);
                }
            }
            currNums.pop();
            return;
        }
        currNums.push(root.val);
        getRes(root.left ,sum,res,curr+root.val,currNums);
        getRes(root.right,sum,res,curr+root.val,currNums);
        currNums.pop();
    }
}