Skip to content

Commit c4f17d9

Browse files
authored
Create 1361. Validate Binary Tree Nodes.cpp
1 parent a9a6e70 commit c4f17d9

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

1361. Validate Binary Tree Nodes.cpp

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
class Solution {
2+
public:
3+
bool validateBinaryTreeNodes(int n, vector<int>& left, vector<int>& right) {
4+
vector<vector<int>> adj(n);
5+
vector<int> ind(n,0);
6+
for(int i=0;i<left.size();i++)
7+
{
8+
if(left[i]!=-1)
9+
{
10+
adj[i].push_back(left[i]);
11+
ind[left[i]]++;
12+
}
13+
}
14+
for(int i=0;i<right.size();i++)
15+
{
16+
if(right[i]!=-1)
17+
{
18+
adj[i].push_back(right[i]);
19+
ind[right[i]]++;
20+
}
21+
}
22+
vector<int> vis(n,0);
23+
queue<int> q;
24+
for(int i=0;i<n;i++)
25+
{
26+
if(ind[i]==0)
27+
{
28+
q.push(i);
29+
break;
30+
}
31+
}
32+
while(!q.empty())
33+
{
34+
int node = q.front();
35+
q.pop();
36+
if(vis[node]!=0)return false;
37+
vis[node] =1;
38+
for(auto it:adj[node])
39+
{
40+
41+
q.push(it);
42+
43+
}
44+
}
45+
for(int i=0;i<n;i++)
46+
{
47+
if(vis[i]==0)return false;
48+
}
49+
return true;
50+
}
51+
};

0 commit comments

Comments
 (0)