-
Notifications
You must be signed in to change notification settings - Fork 2
/
Main34.java
72 lines (66 loc) · 2.11 KB
/
Main34.java
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 JZOffer2;
import java.util.*;
public class Main34 {
List<List<Integer>> res = new LinkedList<>();
Deque<Integer> path = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int target) {
dfs(root, target);
return res;
}
void dfs(TreeNode root, int target){
if(root == null){
return;
}
path.offerLast(root.val);
target -= root.val;
if(root.left == null && root.right == null && target == 0){
res.add(new LinkedList<>(path));
}
dfs(root.left, target);
dfs(root.right, target);
path.pollLast();
}
}
class Main34_1{
List<List<Integer>> ret = new LinkedList<List<Integer>>();
Map<TreeNode, TreeNode> map = new HashMap<TreeNode, TreeNode>();
public List<List<Integer>> pathSum(TreeNode root, int target) {
if(root == null){
return ret;
}
Queue<TreeNode> queueNode = new LinkedList<TreeNode>();
Queue<Integer> queueSum = new LinkedList<Integer>();
queueNode.offer(root);
queueSum.offer(0);
while (!queueNode.isEmpty()){
TreeNode node = queueNode.poll();
int rec = queueSum.poll() + node.val;
if (node.left == null && node.right == null) {
if (rec == target) {
getPath(node);
}
} else {
if(node.left != null){
map.put(node.left, node);
queueNode.offer(node.left);
queueSum.offer(rec);
}
if(node.right != null){
map.put(node.right, node);
queueNode.offer(node.right);
queueSum.offer(rec);
}
}
}
return ret;
}
private void getPath(TreeNode node) {
List<Integer> temp = new LinkedList<Integer>();
while (node != null) {
temp.add(node.val);
node = map.get(node);
}
Collections.reverse(temp);
ret.add(new LinkedList<Integer>(temp));
}
}