forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcheck-if-two-expression-trees-are-equivalent.cpp
95 lines (88 loc) · 2.93 KB
/
check-if-two-expression-trees-are-equivalent.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
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Time: O(n)
// Space: O(h)
// morris traversal
class Solution {
public:
bool checkEquivalence(Node* root1, Node* root2) {
unordered_map<char, int> count;
char prev = '+';
morrisInorderTraversal(root1, bind(&Solution::addCounter, this,
&count, &prev, 1, placeholders::_1));
prev = '+';
morrisInorderTraversal(root2, bind(&Solution::addCounter, this,
&count, &prev, -1, placeholders::_1));
return all_of(cbegin(count), cend(count),
[](const auto& kvp) {
return kvp.second == 0;
});
}
private:
void morrisInorderTraversal(Node *root, const function<void(char)>& cb) {
auto curr = root;
while (curr) {
if (!curr->left) {
cb(curr->val);
curr = curr->right;
} else {
auto node = curr->left;
while (node->right && node->right != curr) {
node = node->right;
}
if (!node->right) {
node->right = curr;
curr = curr->left;
} else {
cb(curr->val);
node->right = nullptr;
curr = curr->right;
}
}
}
}
void addCounter(unordered_map<char, int> *count, char *prev, int d, char val) {
if (isalpha(val)) {
(*count)[val] += (*prev == '+') ? d : -d;
}
*prev = val;
}
};
// Time: O(n)
// Space: O(h)
class Solution2 {
public:
bool checkEquivalence(Node* root1, Node* root2) {
unordered_map<char, int> count;
char prev = '+';
inorderTraversal(root1, bind(&Solution2::addCounter, this,
&count, &prev, 1, placeholders::_1));
prev = '+';
inorderTraversal(root2, bind(&Solution2::addCounter, this,
&count, &prev, -1, placeholders::_1));
return all_of(cbegin(count), cend(count),
[](const auto& kvp) {
return kvp.second == 0;
});
}
private:
void traverseLeft(Node* node, vector<Node *> *stk) {
for (; node; node = node->left) {
stk->emplace_back(node);
}
}
void inorderTraversal(Node *root, const function<void(char)>& cb) {
vector<Node *> stk;
char prev = '+';
traverseLeft(root, &stk);
while (!empty(stk)) {
auto curr = move(stk.back()); stk.pop_back();
cb(curr->val);
traverseLeft(curr->right, &stk);
}
}
void addCounter(unordered_map<char, int> *count, char *prev, int d, char val) {
if (isalpha(val)) {
(*count)[val] += (*prev == '+') ? d : -d;
}
*prev = val;
}
};