-
Notifications
You must be signed in to change notification settings - Fork 0
/
1361. Validate Binary Tree Nodes.cpp
51 lines (49 loc) · 1.14 KB
/
1361. 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
46
47
48
49
50
51
class Solution {
public:
bool validateBinaryTreeNodes(int n, vector<int>& left, vector<int>& right) {
vector<vector<int>> adj(n);
vector<int> ind(n,0);
for(int i=0;i<left.size();i++)
{
if(left[i]!=-1)
{
adj[i].push_back(left[i]);
ind[left[i]]++;
}
}
for(int i=0;i<right.size();i++)
{
if(right[i]!=-1)
{
adj[i].push_back(right[i]);
ind[right[i]]++;
}
}
vector<int> vis(n,0);
queue<int> q;
for(int i=0;i<n;i++)
{
if(ind[i]==0)
{
q.push(i);
break;
}
}
while(!q.empty())
{
int node = q.front();
q.pop();
if(vis[node]!=0)return false;
vis[node] =1;
for(auto it:adj[node])
{
q.push(it);
}
}
for(int i=0;i<n;i++)
{
if(vis[i]==0)return false;
}
return true;
}
};