forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.cpp
34 lines (32 loc) · 892 Bytes
/
Solution.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
class Solution {
public:
vector<int> p;
bool validateBinaryTreeNodes(int n, vector<int>& leftChild, vector<int>& rightChild) {
p.resize(n);
for (int i = 0; i < n; ++i) p[i] = i;
vector<bool> vis(n, false);
for (int i = 0, t = n; i < t; ++i)
{
int l = leftChild[i], r = rightChild[i];
if (l != -1)
{
if (vis[l] || find(i) == find(l)) return false;
vis[l] = true;
p[find(i)] = find(l);
--n;
}
if (r != -1)
{
if (vis[r] || find(i) == find(r)) return false;
vis[r] = true;
p[find(i)] = find(r);
--n;
}
}
return n == 1;
}
int find(int x) {
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
};