这道题的后台测试数据特别水,导致很多错误的代码也可以ac,这里是博主在看了许多其他大佬的代码之后找到的较为简单的正确答案
利用结构体指针队列进行层次遍历,只要节点不为空,就将左右孩子全部入队列(NULL也进),因为是完全二叉树,所以在第一次遇到NULL之前的结点数应该等于总节点数
代码如下:
/*
* ━━━━━━神兽出没━━━━━━
* ┏┓ ┏┓
* ┏┛┻━━━┛┻┓
* ┃ ┃
* ┃ ━ ┃
* ┃ ┳┛ ┗┳ ┃
* ┃ ┃
* ┃ ┻ ┃
* ┃ ┃
* ┗━┓ ┏━┛ Code is far away from bug with the animal's protecting
* ┃ ┃ 神兽保佑,代码无bug
* ┃ ┃
* ┃ ┗━━━┓
* ┃ ┣━┓
* ┃ ┏━┛
* ┗┓┓┏━┳┓┏┛
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛
*
* ━━━━━━大佬带带我━━━━━━
*/
#include<iostream>
#include<stdio.h>
#include<string>
#include<string.h>
#include<math.h>
#include<algorithm>
#include<stdlib.h>
#define MAX 0xfffffff
#define MIN -0xfffffff
#define inf 0x3f3f3f3f
#define LL long long int
#define INIT(a) memset(a,0,sizeof(a))
const double Pi = acos(-1);
const double E = exp(1.0);
const LL mod =1e9+7;
using namespace std;
typedef struct node
{
char data;
struct node *left;
struct node *right;
}Node;
int sum=0;
void creat(Node *&p)
{
char x;
cin>>x;
if(x=='#')return;
sum++;
p=new Node;
p->data =x;
p->left =NULL;
p->right =NULL;
creat(p->left );
creat(p->right );
}
int main()
{
Node *tree;
creat(tree);
Node *dui[1000];
int tou=0,wei=0;
dui[wei]=tree;wei++;
while(tou!=wei)
{
if(dui[tou]==NULL)
{
if(tou==sum)cout<<"Y";
else cout<<"N";
break;
}
dui[wei]=dui[tou]->left ;wei++;
dui[wei]=dui[tou]->right ;wei++;
tou++;
}
return 0;
}