由于没有孩子节点的值是0,所以我命名的序号是1-N,而不是题目给的0-N;所以最后要减去1。
#include <bits/stdc++.h>
using namespace std;
int n, flag = 0;
bool vis[30];
struct node {
int val, lc, rc, pos;
}tree[30];
unordered_map<int, int> mp;
void posName (int root, int pos) {
if (root == 0) return;
tree[root].pos = pos;
mp[pos] = root;
if (pos > n) flag = 1;
posName(tree[root].lc, pos * 2);
posName(tree[root].rc, pos * 2 + 1);
}
int main() {
int root;
string a, b;
scanf ("%d", &n);
for (int i = 1; i <= n; i++) {
cin >> a >> b;
if (a[0] != '-') {
tree[i].lc = stoi(a) + 1;
vis[stoi(a) + 1] = true;
}
else tree[i].lc = 0;
if (b[0] != '-') {
tree[i].rc = stoi(b) + 1;
vis[stoi(b) + 1] = true;
}
else tree[i].rc = 0;
}
for (int i = 1; i < 30; i++) {
if (vis[i] == false) {
root = i;
break;
}
}
posName(root, 1);
if (flag == 0) printf ("YES %d", mp[n] - 1);
else printf ("NO %d", root - 1);
}
|