https://pintia.cn/problem-sets/994805342720868352/problems/994805359372255232
#include <iostream>
#include <cstdio>
#include <queue>
#include <string>
using namespace std;
int n;
struct node {
int lchild;
int rchild;
// int layer;
}Node[22];
//void BFS(int root) {
// queue<int> q;
// q.push(root);
// Node[root].layer = 0;
// while (!q.empty()) {
// int now = q.front();
// q.pop();
// if (Node[now].lchild != -1) {
// int child = Node[now].lchild;
// Node[child].layer = Node[now].layer + 1;
// q.push(child);
// }
// if (Node[now].rchild != -1) {
// int child = Node[now].rchild;
// Node[child].layer = Node[now].layer + 1;
// q.push(child);
// }
// }
//}
int max_index = 0, last = 0;
void preOrder(int v, int index) {
if (v == -1)
return;
if (index > max_index) {
max_index = index;
last = v;
}
preOrder(Node[v].lchild, 2 * index);
preOrder(Node[v].rchild, 2 * index+1);
}
bool hashtable[22];
int main() {
scanf_s("%d", &n);
string l, r;
fill(hashtable, hashtable + 22, false);
getchar();
for (int i = 0; i < n; i++) {
下面要注意,对于读入单个字符
//scanf_s("%c", &l);
//getchar();
//scanf_s("%c", &r);
//getchar();
cin >> l >> r;
if (l != "-") {
Node[i].lchild = atoi(l.c_str());
hashtable[Node[i].lchild] = true;
}
else
Node[i].lchild = -1;
if (r != "-") {
Node[i].rchild = atoi(r.c_str());
hashtable[Node[i].rchild] = true;
}
else
Node[i].rchild = -1;
}
int root = 0;
for (int i = 0; i < n; i++) {
if (hashtable[i] == false) {
root = i;
break;
}
}
/*printf("%d\n", root);*/
preOrder(root, 1);
printf("1,前序遍历解法:\n");
//可以根据 Input 1 推知,若最后遍历得到的max_index > n,则该树不可能是完全二叉树
if (max_index == n) {
cout << "YES " << last << endl;
}
else {
cout << "NO " << root << endl;
}
//BFS解法
printf("2,BFS解法:\n");
//可以根据 Input 2推知,若非最底层的结点不含左右子树时,该树就不可能是完全二叉树
queue<int> q;
q.push(root);
int cnt = 0, lastnode = 0;
while (!q.empty()) {
int temp = q.front();
q.pop();
if (temp != -1) {
lastnode = temp;
cnt++;
}
else {
if (cnt != n) {
printf("NO %d", root);
}
else {
printf("YES %d", lastnode);
}
return 0;
}
q.push(Node[temp].lchild);
q.push(Node[temp].rchild);
}
return 0;
}