Skip to content

Commit f2b9fe1

Browse files
authored
Update Path Sum II.java
1 parent 6cda825 commit f2b9fe1

File tree

1 file changed

+26
-26
lines changed

1 file changed

+26
-26
lines changed

Medium/Path Sum II.java

Lines changed: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -4,36 +4,36 @@
44
* int val;
55
* TreeNode left;
66
* TreeNode right;
7-
* TreeNode(int x) { val = x; }
7+
* TreeNode() {}
8+
* TreeNode(int val) { this.val = val; }
9+
* TreeNode(int val, TreeNode left, TreeNode right) {
10+
* this.val = val;
11+
* this.left = left;
12+
* this.right = right;
13+
* }
814
* }
915
*/
1016
class Solution {
17+
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
1118
List<List<Integer>> list = new ArrayList<>();
12-
public List<List<Integer>> pathSum(TreeNode root, int sum) {
13-
if (root == null) return list;
14-
15-
Stack<Integer> path = new Stack<>();
16-
17-
pathSumImpl(root, sum, path);
18-
return list;
19+
helper(root, targetSum, new ArrayList<>(), list);
20+
return list;
21+
}
22+
23+
private void helper(TreeNode root, int targetSum, List<Integer> curr, List<List<Integer>> list) {
24+
if (root == null) {
25+
return;
1926
}
20-
21-
private void pathSumImpl(TreeNode root, int sum, Stack<Integer> path) {
22-
path.push(root.val);
23-
if (root.left == null && root.right == null) {
24-
if (sum == root.val) {
25-
list.add(new ArrayList<Integer>(path));
26-
}
27-
}
28-
29-
if (root.left != null) {
30-
pathSumImpl(root.left, sum-root.val, path);
31-
}
32-
33-
if (root.right != null) {
34-
pathSumImpl(root.right, sum-root.val, path);
35-
}
36-
37-
path.pop();
27+
curr.add(root.val);
28+
if (isLeaf(root) && (targetSum - root.val) == 0) {
29+
list.add(new ArrayList<>(curr));
3830
}
31+
helper(root.left, targetSum - root.val, curr, list);
32+
helper(root.right, targetSum - root.val, curr, list);
33+
curr.remove(curr.size() - 1);
34+
}
35+
36+
private boolean isLeaf(TreeNode root) {
37+
return root.left == null && root.right == null;
38+
}
3939
}

0 commit comments

Comments
 (0)