forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate-binary-tree-nodes.cpp
38 lines (37 loc) · 1.04 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
// Time: O(n)
// Space: O(n)
class Solution {
public:
bool validateBinaryTreeNodes(int n, vector<int>& leftChild, vector<int>& rightChild) {
unordered_set<int> roots;
for (int i = 0; i < n; ++i) {
roots.emplace(i);
}
for (const auto& i : leftChild) {
roots.erase(i);
}
for (const auto& i : rightChild) {
roots.erase(i);
}
if (roots.size() != 1) {
return false;
}
const auto& root = *cbegin(roots);
vector<int> stk({root});
unordered_set<int> lookup({root});
while (!stk.empty()) {
const auto node = stk.back(); stk.pop_back();
for (const auto& i : {leftChild[node], rightChild[node]}) {
if (i < 0) {
continue;
}
if (lookup.count(i)) {
return false;
}
lookup.emplace(i);
stk.emplace_back(i);
}
}
return true;
}
};