- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1367.java
66 lines (60 loc) · 2.02 KB
/
_1367.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
packagecom.fishercoder.solutions.secondthousand;
importcom.fishercoder.common.classes.ListNode;
importcom.fishercoder.common.classes.TreeNode;
importjava.util.ArrayList;
importjava.util.List;
publicclass_1367 {
publicstaticclassSolution1 {
List<List<Integer>> paths = newArrayList<>();
publicbooleanisSubPath(ListNodehead, TreeNoderoot) {
List<Integer> list = getList(head);
findAllPaths(root, newArrayList<>());
for (List<Integer> path : paths) {
if (path.size() >= list.size()) {
if (find(list, path)) {
returntrue;
}
}
}
returnfalse;
}
privatebooleanfind(List<Integer> list, List<Integer> path) {
inti = 0;
intj = 0;
for (; i <= path.size() - list.size(); i++) {
j = 0;
inttmpI = i;
while (j < list.size() && tmpI < path.size() && list.get(j) == path.get(tmpI)) {
tmpI++;
j++;
}
if (j >= list.size()) {
returntrue;
}
}
returnj >= list.size();
}
privatevoidfindAllPaths(TreeNoderoot, List<Integer> path) {
if (root == null) {
return;
}
path.add(root.val);
if (root.left == null && root.right == null) {
paths.add(newArrayList<>(path));
path.remove(path.size() - 1);
return;
}
findAllPaths(root.left, path);
findAllPaths(root.right, path);
path.remove(path.size() - 1);
}
privateList<Integer> getList(ListNodehead) {
List<Integer> list = newArrayList<>();
while (head != null) {
list.add(head.val);
head = head.next;
}
returnlist;
}
}
}