forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Validate Binary Tree Nodes.cpp
45 lines (36 loc) · 1.03 KB
/
Validate Binary Tree Nodes.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
// Runtime: 112 ms (Top 35.59%) | Memory: 31.8 MB (Top 95.34%)
class Solution {
public:
bool validateBinaryTreeNodes(int n, vector<int>& leftChild, vector<int>& rightChild) {
vector<int> dsu(n, -1);
for(int i = 0; i < n; i++)
{
if(leftChild[i] != -1)
{
if(dsu[leftChild[i]] != -1 || leftChild[i] == findParent(i, dsu))
return false;
dsu[leftChild[i]] = i;
}
if(rightChild[i] != -1)
{
if(dsu[rightChild[i]] != -1 || rightChild[i] == findParent(i, dsu))
return false;
dsu[rightChild[i]] = i;
}
}
int cnt = 0;
for(auto &i : dsu)
if((cnt += i == -1) > 1)
return false;
return true;
}
int findParent(int i, vector<int> &dsu)
{
int a = i;
while(dsu[a] >= 0)
a = dsu[a];
if(dsu[i] != -1)
dsu[i] = a;
return a;
}
};