-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathPseudoPalindromicPath.java
63 lines (58 loc) · 2.05 KB
/
PseudoPalindromicPath.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
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Map;
/**
* 5418. Pseudo-Palindromic Paths in a Binary Tree
* 判断是否回文序列的条件:最多只有一种元素出现的次数为奇数。
* @author LBW
*/
public class PseudoPalindromicPath {
private int result = 0;
public int pseudoPalindromicPaths (TreeNode root) {
ArrayList<Integer> path = new ArrayList<>();
result = 0;
dfs(root, path);
return result;
}
private void dfs(TreeNode root, ArrayList<Integer> path) {
path.add(root.val);
if (root.left == null && root.right == null) { //到叶节点了,path已经构建完毕,可以判断是否为回文序列了。
if (isPseudoPalindrome(path))
result += 1;
}
if (root.left != null)
dfs(root.left, new ArrayList<>(path));
if (root.right != null)
dfs(root.right, new ArrayList<>(path));
}
private boolean isPseudoPalindrome(ArrayList<Integer> path) {
Hashtable<Integer, Integer> hashtable = new Hashtable<>();
for (Integer i: path) {
if (!hashtable.containsKey(i)) {
hashtable.put(i, 1);
}
else {
hashtable.put(i, hashtable.get(i)+1);
}
}
int oddCount = 0;
for (Map.Entry<Integer, Integer> entry: hashtable.entrySet()) {
if (entry.getValue() % 2 == 1)
oddCount += 1;
if (oddCount > 1)
return false;
}
return true;
}
public static void main(String[] args) {
TreeNode root =new TreeNode(2);
root.left = new TreeNode(3);
root.left.left = new TreeNode(3);
root.left.right = new TreeNode(1);
root.right = new TreeNode(1);
root.right.right = new TreeNode(1);
PseudoPalindromicPath pseudoPalindromicPath = new PseudoPalindromicPath();
int result = pseudoPalindromicPath.pseudoPalindromicPaths(root);
System.out.println(result);
}
}