forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution2.cpp
34 lines (34 loc) · 1.02 KB
/
Solution2.cpp
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
/**
* Definition for a binary tree node.
* struct Node {
* char val;
* Node *left;
* Node *right;
* Node() : val(' '), left(nullptr), right(nullptr) {}
* Node(char x) : val(x), left(nullptr), right(nullptr) {}
* Node(char x, Node *left, Node *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool checkEquivalence(Node* root1, Node* root2) {
function<vector<int>(Node*)> dfs = [&](Node* root) -> vector<int> {
vector<int> cnt(26);
if (!root) {
return cnt;
}
if (root->val == '+' || root->val == '-') {
auto l = dfs(root->left);
auto 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;
};
return dfs(root1) == dfs(root2);
}
};