-
Notifications
You must be signed in to change notification settings - Fork 12.3k
Expand file tree
/
Copy pathsolution_1.txt
More file actions
39 lines (35 loc) · 1.22 KB
/
solution_1.txt
File metadata and controls
39 lines (35 loc) · 1.22 KB
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
31
32
33
34
35
36
37
38
39
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
List<List<Integer>> result = new ArrayList<>();
Sum(root, targetSum, result, new ArrayList<Integer>());
return result;
}
private void Sum(TreeNode node, int targetSum, List<List<Integer>> result, ArrayList<Integer> lists){
if (node == null) return;
if (node.left == null && node.right == null && targetSum == node.val) {
lists.add(node.val);
result.add(new ArrayList<Integer>(lists));
lists.remove(lists.size() - 1);
return;
}
lists.add(node.val);
Sum(node.left, targetSum - node.val, result, lists);
Sum(node.right, targetSum - node.val, result, lists);
lists.remove(lists.size() - 1);
}
}