-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetCode1361.cpp
48 lines (48 loc) · 1.25 KB
/
LeetCode1361.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
class Solution
{
public:
int findRoot(int n, vector<int> left, vector<int> right)
{
unordered_set<int> s;
s.insert(left.begin(), left.end());
s.insert(right.begin(), right.end());
for (int i = 0; i < n; i++)
{
if (s.find(i) == s.end())
return i;
}
return -1;
}
bool validateBinaryTreeNodes(int n, vector<int> left, vector<int> right)
{
int root = findRoot(n, left, right);
if (root == -1)
return false;
unordered_set<int> seen;
stack<int> s;
seen.insert(root);
s.push(root);
while (!s.empty())
{
int node = s.top();
s.pop();
int lChild = left[node];
int rChild = right[node];
if (lChild != -1)
{
if (seen.find(lChild) != seen.end())
return false;
seen.insert(lChild);
s.push(lChild);
}
if (rChild != -1)
{
if (seen.find(rChild) != seen.end())
return false;
seen.insert(rChild);
s.push(rChild);
}
}
return seen.size() == n;
}
};