-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.java
30 lines (26 loc) · 949 Bytes
/
Solution.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
if (root != null)
backTrack(root, sum, new ArrayList<Integer>(), res);
return res;
}
public void backTrack(TreeNode root, int target, List<Integer> temp, List<List<Integer>> res) {
temp.add(root.val);
if (root.left == null && root.right == null && root.val == target)
res.add(temp);
if (root.left != null)
backTrack(root.left, target - root.val, new ArrayList<Integer>(temp), res);
if (root.right != null)
backTrack(root.right, target - root.val, new ArrayList<Integer>(temp), res);
}
}