7-7 是否完全二叉搜索树 (30 分)
将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。
输入格式:
输入第一行给出一个不超过20的正整数N
;第二行给出N
个互不相同的正整数,其间以空格分隔。
输出格式:
将输入的N
个正整数顺序插入一个初始为空的二叉搜索树。在第一行中输出结果树的层序遍历结果,数字间以1个空格分隔,行的首尾不得有多余空格。第二行输出YES
,如果该树是完全二叉树;否则输出NO
。
输入样例1:
9
38 45 42 24 58 30 67 12 51
输出样例1:
38 45 24 58 42 30 12 67 51
YES
输入样例2:
8
38 24 12 45 58 67 42 51
输出样例2:
38 45 24 58 42 12 67 51
NO
#include<stdio.h>
#include<stdlib.h>
typedef struct TNode* bintree;
struct TNode{
int data;
bintree left;
bintree right;
};
typedef struct QNode* queue;
struct QNode{
bintree DATATT[100];
int front,rear;
};
queue createqueue(){
queue q = (queue)malloc(sizeof(struct QNode));
q->front = q->rear = 0;
return q;
}
int isempty(queue q){
return (q->front==q->rear);
}
int isfull(queue q){
return (q->rear==100);
}
bintree delete(queue q){
return q->DATATT[++q->front];
}
int add(queue q,bintree t){
if(isfull(q))
return 0;
q->DATATT[++q->rear] = t;
return 1;
}
bintree insert(bintree bst,int x){
if(!bst){
bst = (bintree)malloc(sizeof(struct TNode));
bst->data = x;
bst->left = bst->right = NULL;
}
else {
if(x>bst->data)
bst->left = insert(bst->left,x);
else if(x<bst->data)
bst->right = insert(bst->right,x);
}
return bst;
}
void levelordertraversal(bintree bst,int y){
queue q;
bintree t;
int n = 0;
if(!bst)
return;
q = createqueue();
add(q,bst);
while(!isempty(q)){ //队列不为空
t = delete(q);
printf("%d",t->data);
if(n<y-1){
printf(" ");
n++;
}
if(t->left)
add(q,t->left);
if(t->right)
add(q,t->right);
}
}
int judge(bintree T1,int n){
bintree ttt;
queue q = createqueue();
if(T1==NULL)
return 1;
else{
int count=0;
add(q,T1);
while( (ttt = delete(q))!=NULL ){
add(q,ttt->left);
add(q,ttt->right);
count++;
}
if(count==n)
return 1;
else
return 0;
}
}
int main(){
int x,i,y;
bintree bst = NULL;-
scanf("%d",&y);
for(i=0;i<y;i++){
scanf("%d",&x);
bst = insert(bst,x);
}
levelordertraversal(bst,y);
printf("\n");
if(judge(bst,y))
printf("YES");
else
printf("NO");
return 0;
}