forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path_1457.java
58 lines (53 loc) · 1.85 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
58
package com.fishercoder.solutions;
import com.fishercoder.common.classes.TreeNode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class _1457 {
public static class Solution1 {
public int pseudoPalindromicPaths(TreeNode root) {
List<List<Integer>> allPaths = new ArrayList<>();
List<Integer> path = new ArrayList<>();
dfs(root, path, allPaths);
int result = 0;
for (List<Integer> thisPath : allPaths) {
Map<Integer, Integer> count = findCount(thisPath);
int oddCount = 0;
for (int num : count.keySet()) {
if (count.get(num) % 2 != 0) {
oddCount++;
}
if (oddCount > 1) {
break;
}
}
if (oddCount <= 1) {
result++;
}
}
return result;
}
private void dfs(TreeNode root, List<Integer> path, List<List<Integer>> allPaths) {
if (root.left == null && root.right == null) {
path.add(root.val);
allPaths.add(new ArrayList<>(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);
}
}
private Map<Integer, Integer> findCount(List<Integer> path) {
Map<Integer, Integer> map = new HashMap<>();
path.forEach(i -> map.put(i, map.getOrDefault(i, 0) + 1));
return map;
}
}
}