The background test data of this question is very watery, and many wrong codes can also be ac. Here is the relatively simple correct answer that the blogger found after reading the codes of many other bigwigs.
Use the structure pointer queue for hierarchical traversal. As long as the node is not empty, all the left and right children will be pushed into the stack (NULL is also entered). Because it is a complete binary tree, there should be no non-empty elements after NULL in the queue.
When the head is swept back, it will mark the first NULL after encountering the first NULL. If the mark exists and the node is not empty, it must not be a complete binary tree.
code show as below:
#include<iostream>
using namespace std;
typedef struct Tree
{
char x;
struct Tree *l;
struct Tree *r;
}tree;
void creat(tree *&p)
{
char s;
cin>>s;
if(s=='#')return ;
p=new tree;
p->x=s;
p->l=NULL;
p->r=NULL;
creat(p->l);
creat(p->r);
}
tree *data[100];//队列实现层次遍历
int tou=0;
int wei=0;
bool judge(tree *p)
{
data[0]=p;
wei++;
int flag_N=0;
int flag_F=0;
while(tou!=wei)
{
if(flag_N==1&&data[tou]!=NULL) //NULL后面有非空元素
flag_F=1;
if(data[tou]==NULL&&flag_N==0) //Mark the occurrence of the first NULL
flag_N=1; //Pay attention to the sequence of judging non-null and marking the first NULL if(data[tou]!=NULL ) //Here must be empty { data[wei]=data[tou]->l ; wei++; data[wei]=data[tou]->r ; wei++; } tou++; } if(flag_F==1) return false; else return true; } int main() { tree *p; creat(p); if(judge(p)==true)cout<<"Y"; else cout<<"N"; return 0; }