Skip to content

Commit 0efcf46

Browse files
solves #113 in java
1 parent 20382be commit 0efcf46

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed

Diff for: README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@
105105
| 110 | [Balanced Binary Tree](https://leetcode.com/problems/balanced-binary-tree) | [![Java](assets/java.png)](src/BalancedBinaryTree.java) [![Python](assets/python.png)](python/balanced_binary_tree.py) | |
106106
| 111 | [Minimum Depth of Binary Tree](https://leetcode.com/problems/minimum-depth-of-binary-tree) | [![Java](assets/java.png)](src/MinimumDepthOfBinaryTree.java) [![Python](assets/python.png)](python/minimum_depth_of_binary_tree.py) | |
107107
| 112 | [Path Sum](https://leetcode.com/problems/path-sum) | [![Java](assets/java.png)](src/PathSum.java) [![Python](assets/python.png)](python/path_sum.py) | |
108-
| 113 | [Path Sum II](https://leetcode.com/problems/path-sum-ii) | | |
108+
| 113 | [Path Sum II](https://leetcode.com/problems/path-sum-ii) | [![Java](assets/java.png)](src/PathSumII.java) | |
109109
| 114 | [Flatten Binary Tree to Linked List](https://leetcode.com/problems/flatten-binary-tree-to-linked-list) | | |
110110
| 116 | [Populating Next Right Pointers in Each Node](https://leetcode.com/problems/populating-next-right-pointers-in-each-node) | | |
111111
| 117 | [Populating Next Right Pointers in Each Node II](https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii) | | |

Diff for: src/PathSumII.java

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// https://leetcode.com/problems/path-sum-ii
2+
// T: O(n * log(n))
3+
// S: O(n * log(n))
4+
5+
import java.util.ArrayList;
6+
import java.util.LinkedList;
7+
import java.util.List;
8+
9+
public class PathSumII {
10+
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
11+
final List<List<Integer>> result = new ArrayList<>();
12+
if (root == null) return result;
13+
pathSum(root, targetSum, result);
14+
return result;
15+
}
16+
17+
private void pathSum(TreeNode root, int targetSum, final List<List<Integer>> result) {
18+
pathSum(root, targetSum, result, 0, new LinkedList<>());
19+
}
20+
21+
private void pathSum(TreeNode root, int targetSum, final List<List<Integer>> result, int sum, LinkedList<Integer> path) {
22+
path.addLast(root.val);
23+
sum += root.val;
24+
25+
if (isLeafNode(root)) {
26+
if (sum == targetSum) result.add(new ArrayList<>(path));
27+
return;
28+
}
29+
30+
if (root.left != null) {
31+
pathSum(root.left, targetSum, result, sum, path);
32+
path.removeLast();
33+
}
34+
if (root.right != null) {
35+
pathSum(root.right, targetSum, result, sum, path);
36+
path.removeLast();
37+
}
38+
}
39+
40+
private boolean isLeafNode(TreeNode root) {
41+
return root.left == null && root.right == null;
42+
}
43+
}

0 commit comments

Comments
 (0)