#include<stdio.h>
#include<stdlib.h>
#define OK 1
#define ERROR 0
bool ISGO=true;//全局变量
//首先,构建二叉链表的结构体
typedef struct BiList{
int data;
struct BiList *Lchild,*Rchild;
}BiList,*BiLinkList;
//对二叉链表进行添加孩子的函数,这里把它写成手动添加,其主要目的是验证判断函数是否正常使用,不是重点
int InLinkList(BiLinkList &B,char a[],int e){
BiList *temp=B;
BiList *p;
p=new BiList;
p->data=e;
p->Rchild=NULL;
p->Lchild=NULL;
if(strcmp(a,"L")==0){
temp->Lchild=p;
temp=temp->Lchild;
printf("插入成功\n");
return OK;
}
if(strcmp(a,"R")==0){
temp->Rchild=p;
temp=temp->Rchild;
printf("插入成功\n");
return OK;
}
return ERROR;
}
//判断是否是正则二叉树
int Judge(BiLinkList B){
if(!ISGO){
return ERROR;
}
BiLinkList p=B;
if(!p->Lchild&&!p->Rchild){
printf("叶子结点\n");
return OK;
}
if(!p->Lchild&&p->Rchild){
ISGO=false;
return ERROR;
}else if(p->Lchild&&!p->Rchild){
ISGO=false;
return ERROR;
}
Judge(p->Lchild);
Judge(p->Rchild);
return OK;
}
//主函数
int main(){
/* 这些都是构建一个二叉链表,方便我们验证是否成功 */
BiList *B,*temp;
InitBiList(B,5);
char L[]="L";
char R[]="R";
InLinkList(B,L,6);
InLinkList(B,R,7);
temp=B->Lchild;
InLinkList(temp,L,8);
InLinkList(temp,R,9);
temp=B->Rchild;
InLinkList(temp,L,10);
InLinkList(temp,R,11);
Judge(B);
if(ISGO){
printf("B是一棵正则二叉树\n");
}else{
printf("B不是一棵正则二叉树\n");
}
}
运行结果
这里使用一个全局变量ISGO来判断是否为正则二叉树,如果ISGO=true表示该二叉树为正则二叉树,反之,则不是正则二叉树。
函数是利用递归来遍历二叉链表,对每一个节点进行判断,如果该结点只有一个孩子,就把全局变量 ISGO 设为 false。