-
Notifications
You must be signed in to change notification settings - Fork 0
/
Path Sum2.java
35 lines (35 loc) · 1.3 KB
/
Path Sum2.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
31
32
33
34
35
https://leetcode.com/problems/path-sum-ii
/**
* 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<Integer> currentPath = new ArrayList();
List<List<Integer>> allPaths = new ArrayList();
findPathsRecursive(root,targetSum,currentPath,allPaths);
return allPaths;
}
private static void findPathsRecursive(TreeNode currentNode, int sum, List<Integer> currentPath,List<List<Integer>> allPaths){
if(currentNode==null)return;
currentPath.add(currentNode.val);
if(currentNode.val==sum && currentNode.left==null && currentNode.right==null)
allPaths.add(new ArrayList<Integer>(currentPath));
else{
findPathsRecursive(currentNode.left,sum-currentNode.val,currentPath,allPaths);
findPathsRecursive(currentNode.right,sum-currentNode.val,currentPath,allPaths);
}
currentPath.remove(currentPath.size()-1);
}
}