-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
35 lines (31 loc) · 1.05 KB
/
main.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
class Solution {
public:
bool validateBinaryTreeNodes(int n, vector<int>& leftChild,
vector<int>& rightChild) {
vector<bool> hasParent(n, false);
for (int i = 0; i < n; ++i) {
if (leftChild[i] != -1) hasParent[leftChild[i]] = true;
if (rightChild[i] != -1) hasParent[rightChild[i]] = true;
}
int root = -1;
for (int i = 0; i < n; ++i) {
if (hasParent[i]) continue;
if (root != -1) return false;
root = i;
}
if (root == -1) return false;
vector<bool> vis(n, false);
function<bool(int)> dfs = [&](int u) -> bool {
if (vis[u]) return false;
vis[u] = true;
if (leftChild[u] != -1 && !dfs(leftChild[u])) return false;
if (rightChild[u] != -1 && !dfs(rightChild[u])) return false;
return true;
};
if (!dfs(root)) return false;
for (bool b : vis) {
if (!b) return false;
}
return true;
}
};