/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public void backtracking(TreeNode node, int target, ArrayList<Integer> path, List<List<Integer>> res) {
if (node == null) {
return;
}
path.add(node.val);
target -= node.val;
if (target == 0 && node.left == null && node.right == null) {
res.add(new ArrayList<Integer>(path));
} else {
backtracking(node.left, target, path, res);
backtracking(node.right, target, path, res);
}
path.remove(path.size() - 1);
}
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
backtracking(root, sum, new ArrayList<Integer>(), res);
return res;
}
}