Java:
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> ans = new LinkedList<>();
List<Integer> result = new LinkedList<>();
path(root, sum, ans, result);
return ans;
}
public void path(TreeNode root, int sum, List<List<Integer>> ans, List<Integer> result){
if(root == null) return;
result.add(new Integer(root.val));
if(root.left == null && root.right == null && sum == root.val){
ans.add(new LinkedList(result));
result.remove(result.size()-1);
return;
}
else{
path(root.left, sum-root.val, ans, result);;
path(root.right, sum-root.val, ans, result);
}
result.remove(result.size()-1);
}
}
Python:
class Solution:
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
if not root:
return []
result, ans = [], []
self.path(root, sum, ans, result)
return ans
def path(self, root, sum, ans, result):
if not root.left and not root.right and root.val == sum:
result.append(root.val)
ans.append(result)
if root.left:
self.path(root.left, sum-root.val, ans, result+[root.val])
if root.right:
self.path(root.right, sum-root.val, ans, result+[root.val])