-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathSum.java
More file actions
72 lines (57 loc) · 2.08 KB
/
PathSum.java
File metadata and controls
72 lines (57 loc) · 2.08 KB
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package BackTracking;
import java.util.*;
public class PathSum {
static class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}
public static void main(String[] args) {
// Build sample tree:
// 5
// / \
// 4 8
// / / \
// 11 13 4
// / \ / \
// 7 2 5 1
TreeNode root = new TreeNode(5);
root.left = new TreeNode(4);
root.right = new TreeNode(8);
root.left.left = new TreeNode(11);
root.left.left.left = new TreeNode(7);
root.left.left.right = new TreeNode(2);
root.right.left = new TreeNode(13);
root.right.right = new TreeNode(4);
root.right.right.left = new TreeNode(5);
root.right.right.right = new TreeNode(1);
int targetSum = 22;
PathSum demo = new PathSum();
List<List<Integer>> result = demo.pathSum(root, targetSum);
System.out.println("Paths with sum " + targetSum + ":");
for (List<Integer> path : result) {
System.out.println(path);
}
}
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
List<List<Integer>> pathSum = new ArrayList<>();
backTrack(root, targetSum, 0, new ArrayList<>(), pathSum);
return pathSum;
}
static void backTrack(TreeNode root, int targetSum, int sum, List<Integer> path, List<List<Integer>> pathSum) {
if (root == null) return;
sum += root.val;
path.add(root.val);
backTrack(root.left, targetSum, sum, path, pathSum);
backTrack(root.right, targetSum, sum, path, pathSum);
if (root.left == null && root.right == null && sum == targetSum) {
pathSum.add(new ArrayList<>(path));
}
path.remove(path.size() - 1);
}
}
// Input: root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
// Output: [[5,4,11,2],[5,8,4,5]]
// Explanation: There are two paths whose sum equals targetSum:
// 5 + 4 + 11 + 2 = 22
// 5 + 8 + 4 + 5 = 22