-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy path1110_Complete Binary Tree (25).cpp
52 lines (48 loc) · 1.28 KB
/
1110_Complete Binary Tree (25).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
52
/*
1. 使用二维数组,[节点]-{[0]左孩子,[1]右孩子,[2]节点入度}
2. 根的入度为0
3. 层次遍历判断节点id关系是否连续
*/
#include <bits/stdc++.h>
using namespace std;
int tree[25][3]; // 左,右,入度
int main() {
int n;
string str[2];
cin >> n;
for (int i = 0; i < n; i++) {
tree[i][0] = tree[i][1] = -1;
tree[i][2] = 0;
}
for (int i = 0; i < n; i++) {
cin >> str[0] >> str[1];
for (int j = 0; j < 2; j++) {
if (str[j] != "-") {
int val = stoi(str[j]);
tree[i][j] = val;
tree[val][2]++;
}
}
}
int root = -1;
for (int i = 0; i < n; i++) {
if (tree[i][2] == 0) root = i;
}
int previd = 0, ok = true, cur = -1;
queue<pair<int, int>> q;
q.push({root, 1});
while (!q.empty()) {
int curid = q.front().second;
cur = q.front().first;
q.pop();
if (curid - previd != 1) { ok = false; break; }
previd = curid;
if (tree[cur][0] != -1) q.push({tree[cur][0], curid*2});
if (tree[cur][1] != -1) q.push({tree[cur][1], curid*2 + 1});
}
if (ok)
cout << "YES " << cur << endl;
else
cout << "NO " << root << endl;
return 0;
}