0%

1361. Validate Binary Tree Nodes

union-find O(n) time O(n) space
合法的树只有一个连通组件,因为点数和边数之差为1

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
class Solution {
public:
bool validateBinaryTreeNodes(int n, vector<int>& leftChild, vector<int>& rightChild) {
parent.resize(n);
iota(begin(parent), end(parent), 0);
cnt = n;
for (int i = 0; i < n; ++i) {
if (!merge(i, leftChild[i])) return false;
if (!merge(i, rightChild[i])) return false;
}
return cnt == 1;
}

int find(int x) {
while (x != parent[x]) {
x = parent[x] = parent[parent[x]];
}
return x;
}

bool merge(int x, int y) {
if (y == -1) return true; // 注意-1的情况!!!
int px = find(x), py = find(y);
if (px == py) return false;
parent[px] = py;
--cnt;
return true;
}

int cnt;
vector<int> parent;
};