1. 题目
判断是否完全二叉树
2. 代码
- 因为index可能有两位数,不能使用
char c
,应该使用string
或者char c[3]
。建议使用string
比较方便。但是不管哪种都要吸收换行符。 - 根据是否有父节点判断是否是根结点,这点很常用
1. 使用层序遍历
#include <iostream>
#include <string>
#include <queue>
using namespace std;
const int maxn = 30;
struct node {
int lchild, rchild;
} Node[maxn];
int N;
bool have_father[maxn] = {false};
int cnt = 1, last = -1;
void layerOrder(int root) { //完全二叉树左孩子结点 2*i
queue<int> q;
q.push(root);
last = root;
while (!q.empty()) {
int front = q.front();
q.pop();
if (Node[front].lchild != -1) {
cnt++;
last = Node[front].lchild;
q.push(Node[front].lchild);
} else break;
if (Node[front].rchild != -1) {
cnt++;
last = Node[front].rchild;
q.push(Node[front].rchild);
} else break;
}
if (cnt == N) printf("YES %d\n", last);
else printf("NO %d\n", root);
}
int main() {
cin >> N;
for (int i = 0; i < N; ++i) { //编号从0开始
cin.ignore();
string str1, str2;
cin >> str1 >> str2;
if (str1 != "-") { //如果有左孩子
Node[i].lchild = stoi(str1);
have_father[stoi(str1)] = true;
} else {
Node[i].lchild = -1;
}
if (str2 != "-") { //如果有右孩子
Node[i].rchild = stoi(str2);
have_father[stoi(str2)] = true;
} else {
Node[i].rchild = -1;
}
}
int root=-1;
for (int i = 0; i < N; ++i) { //没有父结点的就是根结点
if (!have_father[i]) {
root = i;
break;
}
}
layerOrder(root);
return 0;
}
2. 使用DFS
- 这里搬运了柳神代码
#include <iostream>
#include <string>
using namespace std;
struct node {
int lchild, rchild;
} Node[1010];
int maxn = -1, ans;
void DFS(int root, int index) {
if (index > maxn) {
maxn = index;
ans = root;
}
if (Node[root].lchild != -1) DFS(Node[root].lchild, index * 2);
if (Node[root].rchild != -1) DFS(Node[root].rchild, index * 2 + 1);
}
int main() {
int n, root = 0;
bool have_child[1010] = {false};
scanf("%d", &n);
for (int i = 0; i < n; i++) {
string lchild, rchild;
cin >> lchild >> rchild;
if (lchild == "-") Node[i].lchild = -1;
else {
Node[i].lchild = stoi(lchild);
have_child[stoi(lchild)] = true;
}
if (rchild == "-") Node[i].rchild = -1;
else {
Node[i].rchild = stoi(rchild);
have_child[stoi(rchild)] = true;
}
}
while (have_child[root]) root++;
DFS(root, 1);
if (maxn == n) printf("YES %d", ans);
else printf("NO %d", root);
return 0;
}