forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
number-of-ways-to-reconstruct-a-tree.cpp
46 lines (45 loc) · 1.44 KB
/
number-of-ways-to-reconstruct-a-tree.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
// Time: O(nlogn)
// Space: O(n)
class Solution {
public:
int checkWays(vector<vector<int>>& pairs) {
unordered_map<int, unordered_set<int>> adj;
for (const auto& pair : pairs) {
adj[pair[0]].emplace(pair[1]);
adj[pair[1]].emplace(pair[0]);
}
int n = size(adj);
bool mul = false;
unordered_set<int> lookup;
vector<int> nodes;
transform(begin(adj), end(adj), back_inserter(nodes),
[](const auto& kvp) { return kvp.first; });
sort(begin(nodes), end(nodes),
[&adj](const auto& a, const auto& b) {
return size(adj[a]) > size(adj[b]);
});
for (const auto& node : nodes) {
lookup.emplace(node);
int parent = 0;
for (const auto& x : adj[node]) {
if (!lookup.count(x)) {
continue;
}
if (parent == 0 || size(adj[x]) < size(adj[parent])) {
parent = x;
}
}
if (parent) {
for (const auto& x : adj[node]) {
if (x != parent && !adj[parent].count(x)) {
return 0;
}
}
mul |= size(adj[node]) == size(adj[parent]);
} else if (size(adj[node]) != n - 1) {
return 0;
}
}
return 1 + mul;
}
};