forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_1367.java
67 lines (60 loc) · 2.01 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
67
package com.fishercoder.solutions;
import com.fishercoder.common.classes.ListNode;
import com.fishercoder.common.classes.TreeNode;
import java.util.ArrayList;
import java.util.List;
public class _1367 {
public static class Solution1 {
List<List<Integer>> paths = new ArrayList<>();
public boolean isSubPath(ListNode head, TreeNode root) {
List<Integer> list = getList(head);
findAllPaths(root, new ArrayList<>());
for (List<Integer> path : paths) {
if (path.size() >= list.size()) {
if (find(list, path)) {
return true;
}
}
}
return false;
}
private boolean find(List<Integer> list, List<Integer> path) {
int i = 0;
int j = 0;
for (; i <= path.size() - list.size(); i++) {
j = 0;
int tmpI = i;
while (j < list.size() && tmpI < path.size() && list.get(j) == path.get(tmpI)) {
tmpI++;
j++;
}
if (j >= list.size()) {
return true;
}
}
return j >= list.size();
}
private void findAllPaths(TreeNode root, List<Integer> path) {
if (root == null) {
return;
}
path.add(root.val);
if (root.left == null && root.right == null) {
paths.add(new ArrayList<>(path));
path.remove(path.size() - 1);
return;
}
findAllPaths(root.left, path);
findAllPaths(root.right, path);
path.remove(path.size() - 1);
}
private List<Integer> getList(ListNode head) {
List<Integer> list = new ArrayList<>();
while (head != null) {
list.add(head.val);
head = head.next;
}
return list;
}
}
}