-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathSum.java
More file actions
52 lines (48 loc) · 1.61 KB
/
PathSum.java
File metadata and controls
52 lines (48 loc) · 1.61 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
package com.interview.tree;
import java.util.ArrayList;
import java.util.List;
/**
* Date 10/06/2016
* @author Tushar Roy
*
* Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
*
* Time complexity O(n)
*
* https://leetcode.com/problems/path-sum/
* https://leetcode.com/problems/path-sum-ii/
*/
public class PathSum {
public List<List<Integer>> pathSum(Node root, int sum) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> current = new ArrayList<>();
pathSumUtil(root, sum, result, current);
return result;
}
private void pathSumUtil(Node root, int sum, List<List<Integer>> result, List<Integer> currentPath) {
if (root == null) {
return;
}
if (root.left == null && root.right == null) {
if (root.data == sum) {
currentPath.add(root.data);
result.add(new ArrayList<>(currentPath));
currentPath.remove(currentPath.size() - 1);
}
return;
}
currentPath.add(root.data);
pathSumUtil(root.left, sum - root.data, result, currentPath);
pathSumUtil(root.right, sum - root.data, result, currentPath);
currentPath.remove(currentPath.size() - 1);
}
public boolean hasPathSum(Node root, int sum) {
if (root == null) {
return false;
}
if (root.left == null && root.right == null) {
return root.data == sum;
}
return hasPathSum(root.left, sum - root.data) || hasPathSum(root.right, sum - root.data);
}
}