【问题描述】
给定一个树,请你判断它是否是完全二叉树。
【输入格式】
第一行包含整数 N,表示树的结点个数。
树的结点编号为 0∼N−1。
接下来 N 行,每行对应一个结点,并给出该结点的左右子结点的编号,如果某个子结点不存在,则用 - 代替。
【输出格式】
如果是完全二叉树,则输出 YES 以及最后一个结点的编号。
如果不是,则输出 NO 以及根结点的编号。
【数据范围】
1≤N≤20
【输入样例1】
9
7 8
- -
- -
- -
0 1
2 3
4 5
- -
- -
【输出样例1】
YES 8
【输入样例2】
8
- -
4 5
0 6
- -
2 3
- 7
- -
- -
【输出样例2】
NO 1
【算法代码】
#include <bits/stdc++.h>
using namespace std;
const int N=25;
int n;
int le[N],ri[N];
bool has_father[N];
int maxk,maxid;
void dfs(int u, int k) {
if(u==-1) return;
if(k>maxk) {
maxk=k;
maxid=u;
}
dfs(le[u], k*2);
dfs(ri[u], k*2+1);
}
int main() {
memset(le,-1,sizeof(le));
memset(ri,-1,sizeof(ri));
cin>>n;
for(int i=0; i<n; i++) {
string a,b;
cin>>a>>b;
if(a!="-") le[i]=atoi(a.c_str()), has_father[le[i]]=true;
if(b!="-") ri[i]=atoi(b.c_str()), has_father[ri[i]]=true;
}
int root=0;
while(has_father[root]) root++; //find root
dfs(root,1);
if(maxk==n) cout<<"YES"<<" "<<maxid;
else cout<<"NO"<<" "<<root;
return 0;
}
/*
in1:
9
7 8
- -
- -
- -
0 1
2 3
4 5
- -
- -
out1:
YES 8
--------
in2:
8
- -
4 5
0 6
- -
2 3
- 7
- -
- -
out2:
NO 1
*/
【参考文献】
https://blog.csdn.net/shizheng_Li/article/details/113173597
https://blog.csdn.net/qq_43738331/article/details/115988329
https://www.acwing.com/problem/content/1602/
https://blog.csdn.net/weixin_43847596/article/details/113751978