Skip to content

Commit 68ba5b5

Browse files
committed
add solution of problem 113: path sum II
1 parent 7058f43 commit 68ba5b5

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

PathSumII113/README.md

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
2+
3+
For example:
4+
Given the below binary tree and `sum = 22`,
5+
6+
```
7+
8+
5
9+
/ \
10+
4 8
11+
/ / \
12+
11 13 4
13+
/ \ / \
14+
7 2 5 1
15+
```
16+
17+
return
18+
19+
```
20+
21+
[
22+
[5,4,11,2],
23+
24+
[5,8,4,5]
25+
26+
]
27+
28+
```

PathSumII113/Solution.java

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* public class TreeNode {
4+
* int val;
5+
* TreeNode left;
6+
* TreeNode right;
7+
* TreeNode(int x) { val = x; }
8+
* }
9+
*/
10+
public class Solution {
11+
public List<List<Integer>> pathSum(TreeNode root, int sum) {
12+
List<List<Integer>> result = new ArrayList<List<Integer>>();
13+
14+
if (root == null)
15+
return result;
16+
17+
Stack<Integer> path = new Stack<Integer>();
18+
preOrder(root, path, result, 0, sum);
19+
return result;
20+
}
21+
22+
private final void preOrder(TreeNode node, Stack<Integer> path, List<List<Integer>> result, int currSum, int expectedSum) {
23+
path.push(node.val);
24+
currSum += node.val;
25+
26+
if (node.left == null && node.right == null && currSum == expectedSum) {
27+
if (currSum == expectedSum) {
28+
List<Integer> pathList = new ArrayList<Integer>();
29+
for (int val : path) {
30+
pathList.add(val);
31+
}
32+
33+
result.add(pathList);
34+
}
35+
}
36+
37+
if (node.left != null) {
38+
preOrder(node.left, path, result, currSum, expectedSum);
39+
}
40+
41+
if (node.right != null) {
42+
preOrder(node.right, path, result, currSum, expectedSum);
43+
}
44+
45+
path.pop();
46+
}
47+
}

0 commit comments

Comments
 (0)