-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathSum.java
More file actions
31 lines (26 loc) · 824 Bytes
/
PathSum.java
File metadata and controls
31 lines (26 loc) · 824 Bytes
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
import java.util.LinkedList;
import java.util.List;
/**
* 113. 二叉树中和为某一值的路径
*/
public class PathSum {
public List<List<Integer>> pathSum(TreeNode root, int target) {
List<List<Integer>> res = new LinkedList<>();
dp(root, target, new LinkedList<Integer>(), (LinkedList)res);
return res;
}
void dp(TreeNode root, int target, LinkedList<Integer> temp, LinkedList<LinkedList<Integer>> res){
if(target==0 && temp.size()>0){
res.add(new LinkedList<>(temp));
}
if(root==null){
return;
}
temp.add(root.val);
dp(root.left, target-root.val, temp, res);
temp.removeLast();
temp.add(root.val);
dp(root.right, target-root.val, temp, res);
temp.removeLast();
}
}