-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0113. Path Sum II
54 lines (49 loc) · 1.81 KB
/
0113. Path Sum II
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* 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 {
// Time Complexity: O(n^2)
// In the worst case, the tree is a complete binary tree with n nodes. For each node, we traverse all the way down a path till leaf, which takes O(n) time. And there can be n paths in the worst case. So the overall time complexity is O(n^2).
// Space Complexity: O(n)
// The recursion stack depth can go upto n in the worst case. Additionally, the curr list storing the path can contain at most n nodes. So the overall space complexity is O(n).
public void helper(int target, TreeNode root, List<Integer> curr, List<List<Integer>> res){
if (root == null) {
return;
}
target -= root.val;
if (target == 0 && root.left == null && root.right == null) {
ArrayList<Integer> newCurr = new ArrayList<>(curr);
newCurr.add(root.val);
res.add(newCurr);
return;
}
else {
curr.add(root.val);
helper(target, root.left, curr, res);
helper(target, root.right, curr, res);
curr.remove(curr.size() - 1);
return;
}
}
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) {
return res;
}
List<Integer> curr = new ArrayList<>();
helper(targetSum, root, curr, res);
return res;
}
}