本题运用到了树的静态写法来创建树,二叉树的层序遍历来检验该二叉树是否为完全二叉树
在层序遍历中,如果遇到结点为空的情况(在代码中表示为-1)的情况,则说明该树不是一棵完全二叉树,,则输出 No和根节点;如果遍历了全部的结点(均不为空),则输出Yes和最后一个结点
这是我之前刷 PTA(Advanced Level) 其他有关树的题目,从《算法笔记上机训练实战指南》中学习到如何获取根节点的方法,在这里提一下
获得二叉树的根节点编号,即0~(N-1)中未在输入中出现过的那个数。
代码如下
#include <cstdio>
#include <queue>
using namespace std;
const int maxn=22;
bool vis[maxn]={false};
int n, last, ans=0;
bool flag=true;
struct node{
int lchild, rchild;
}no[maxn];
void bfs(int root){
queue<int> q;
q.push(root);
while(!q.empty()){
int front=q.front();
q.pop();
if(front==-1){
flag=false;
break;
}
if(ans==(n-1)){
last=front;
break;
}
ans+=1;
q.push(no[front].lchild);
q.push(no[front].rchild);
}
}
int main()
{
scanf("%d", &n);
getchar();
for(int i=0; i<n; i++){
int x=0;
char temp=getchar();
while(temp!=' '){
if(temp=='-'){
x=-1;
} else {
x=x*10+(temp-'0');
}
temp=getchar();
}
no[i].lchild=x;
if(x!=-1)
vis[x]=true;
temp=getchar();
x=0;
while(temp!='\n'){
if(temp=='-'){
x=-1;
} else {
x=x*10+(temp-'0');
}
temp=getchar();
}
no[i].rchild=x;
if(x!=-1)
vis[x]=true;
}
int root;
for(int i=0; i<n; i++){
if(!vis[i]){
root=i;
break;
}
}
bfs(root);
if(flag)
printf("YES %d\n", last);
else
printf("NO %d\n", root);
return 0;
}