-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path0376. Binary Tree Path Sum.java
More file actions
52 lines (48 loc) · 1.44 KB
/
0376. Binary Tree Path Sum.java
File metadata and controls
52 lines (48 loc) · 1.44 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
**
* Definition of TreeNode:
* public class TreeNode {
* public int val;
* public TreeNode left, right;
* public TreeNode(int val) {
* this.val = val;
* this.left = this.right = null;
* }
* }
*/
public class Solution {
/*
* @param root: the root of binary tree
* @param target: An integer
* @return: all valid paths
*/
public List<List<Integer>> binaryTreePathSum(TreeNode root, int target) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
path.add(root.val);
helper(root, result, path, target);
return result;
}
public void helper(TreeNode root, List<List<Integer>> result, List<Integer> path, int target){
if(root.left == null && root.right == null){
if(sum(path) == target){
result.add(new ArrayList<>(path)); //must be a clone!
return;
}
}
if(root.left != null){
path.add(root.left.val);
helper(root.left, result, path, target);
path.remove(path.size() - 1);
}
if(root.right != null){
path.add(root.right.val);
helper(root.right, result, path, target);
path.remove(path.size() - 1);
}
}
public int sum(List<Integer> path){
int result = 0;
for(int n : path) result += n;
return result;
}
}