- Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_1457.java
57 lines (53 loc) · 1.87 KB
/
_1457.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
packagecom.fishercoder.solutions.secondthousand;
importcom.fishercoder.common.classes.TreeNode;
importjava.util.ArrayList;
importjava.util.HashMap;
importjava.util.List;
importjava.util.Map;
publicclass_1457 {
publicstaticclassSolution1 {
publicintpseudoPalindromicPaths(TreeNoderoot) {
List<List<Integer>> allPaths = newArrayList<>();
List<Integer> path = newArrayList<>();
dfs(root, path, allPaths);
intresult = 0;
for (List<Integer> thisPath : allPaths) {
Map<Integer, Integer> count = findCount(thisPath);
intoddCount = 0;
for (intnum : count.keySet()) {
if (count.get(num) % 2 != 0) {
oddCount++;
}
if (oddCount > 1) {
break;
}
}
if (oddCount <= 1) {
result++;
}
}
returnresult;
}
privatevoiddfs(TreeNoderoot, List<Integer> path, List<List<Integer>> allPaths) {
if (root.left == null && root.right == null) {
path.add(root.val);
allPaths.add(newArrayList<>(path));
return;
}
path.add(root.val);
if (root.left != null) {
dfs(root.left, path, allPaths);
path.remove(path.size() - 1);
}
if (root.right != null) {
dfs(root.right, path, allPaths);
path.remove(path.size() - 1);
}
}
privateMap<Integer, Integer> findCount(List<Integer> path) {
Map<Integer, Integer> map = newHashMap<>();
path.forEach(i -> map.put(i, map.getOrDefault(i, 0) + 1));
returnmap;
}
}
}