-
-
Notifications
You must be signed in to change notification settings - Fork 9k
/
Copy pathSolution.java
45 lines (44 loc) · 1.11 KB
/
Solution.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
/**
* Definition for a binary tree node.
* class Node {
* char val;
* Node left;
* Node right;
* Node() {this.val = ' ';}
* Node(char val) { this.val = val; }
* Node(char val, Node left, Node right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean checkEquivalence(Node root1, Node root2) {
int[] cnt1 = dfs(root1);
int[] cnt2 = dfs(root2);
for (int i = 0; i < 26; ++i) {
if (cnt1[i] != cnt2[i]) {
return false;
}
}
return true;
}
private int[] dfs(Node root) {
int[] cnt = new int[26];
if (root == null) {
return cnt;
}
if (root.val == '+' || root.val == '-') {
int[] l = dfs(root.left);
int[] r = dfs(root.right);
int k = root.val == '+' ? 1 : -1;
for (int i = 0; i < 26; ++i) {
cnt[i] += l[i] + r[i] * k;
}
} else {
cnt[root.val - 'a']++;
}
return cnt;
}
}