Example:
Given the below binary tree and
sum = 22
,5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
Return:
[ [5,4,11,2], [5,8,4,5] ]
//
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
if (root == null) {
return new ArrayList<>();
}
List<List<Integer>> result = new ArrayList<>();
backtrack(result, new ArrayList<>(), root, sum);
return result;
}
void backtrack(List<List<Integer>> result, List<Integer> tempList, TreeNode root, int sum) {
if (root == null) {
return;
}
tempList.add(root.val);
if (root.left == null && root.right == null && root.val == sum) {
result.add(new ArrayList<>(tempList));
} else {
int remain = sum - root.val;
backtrack(result, tempList, root.left, remain);
backtrack(result, tempList, root.right, remain);
}
tempList.remove(tempList.size() - 1);
}
}