题目描述
我们定义:二叉树每一层中,节点最多的那层的节点数为二叉树的宽度。 请编写一个程序计算二叉树的宽度。
输入
每行是一棵二叉树的带虚结点(#)表示的前序遍历序串,长度不超过2000。每个结点为一个小写字母或一个数字。
输出
对于每行输入的二叉树,输出该二叉树的宽度,每个结果占一行。
样例输入
#
a#bc##f##
样例输出
0
2
提示
第一行输入的为空二叉树,其宽度为零。
#include < stdio.h>
#include < stdlib.h>
#define OK 1
#define error 0
#define overflow 0
typedef int Status;
typedef struct BiTNode{
char data;
struct BiTNode *leftchild;
struct BiTNode *rightchild;
}BiTNode,*BiTree;
void InitTree(BiTree *T){
*T=NULL;
}
int z=0;
Status CreateBiTree(BiTree *T,char s[]){
char ch;
ch=s[z];
z++;
if(ch=='#')
*T=NULL;
else{
(*T)=(BiTree)malloc(sizeof(BiTNode));
if(!(*T))
exit(overflow);
(*T)->data=ch;
CreateBiTree(&(*T)->leftchild,s);
CreateBiTree(&(*T)->rightchild,s);
}
return OK;
}///这里是建立树
typedef BiTree QElemType;
typedef struct QNode{
QElemType content;
struct QNode *next;
}QNode,*QueuePtr;
typedef struct{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
Status InitQueue(LinkQueue *q){
q->front=q->rear=(QueuePtr)malloc(sizeof(QNode));
if(!(q->front))
exit(overflow);
q->front->next=NULL;
return OK;
}//初始化
Status EnQueue(LinkQueue *q,QElemType *T){
QueuePtr p,s;
p=(QueuePtr)malloc(sizeof(QNode));
if(!p)
exit(overflow);
p->content=*T;
p->next=NULL;
q->rear->next=p;
q->rear=p;
s=q->front->next;
return OK;
}
Status DeQueue(LinkQueue *q, QElemType *e){
QueuePtr p;
if(q->front==q->rear)
return error;
p=q->front->next;
*e=p->content;
q->front->next=p->next;
if(q->rear==p)
q->rear=q->front;
free(p);
return OK;
}//出队
Status GetTop(LinkQueue *q, QElemType *e){
QueuePtr p;
if(q->front==q->rear)
return error;
p=q->front->next;
*e=p->content;
return OK;
}//取栈顶元素
Status IsEmpty(LinkQueue *q){
if(q->front==q->rear)
return OK;
else
return error;
}////这里是链式队列的库
Status WidthBiTree(BiTree T){
LinkQueue q;
QElemType tmp,p;
p=T;
int a[20]={0};
a[0]=1;
int pre=0,pos=1,end=0;
int level=1;
EnQueue(&q,&p);
end++;
while(!IsEmpty(&q)){
DeQueue(&q,&tmp);
pre++;
if(tmp->leftchild){
EnQueue(&q,&tmp->leftchild);
end++;
}
if(tmp->rightchild){
EnQueue(&q,&tmp->rightchild);
end++;
}
if(pre==pos){
a[level]=end-pos;
level++;
pos=end;
}
}
int i,max;
max=0;
for(i=0;i< level;i++){
if(a[i]>max)
max=a[i];
}
return max;
}///求宽度
void PreOrder(BiTree T){
if(T){
printf("%c",T->data);
PreOrder(T->leftchild);
PreOrder(T->rightchild);
}
}
char s[2000];
int main()
{
BiTree T;
int width,n;
scanf("%d",&n);
while(n--){
z=0;
scanf("%s",s);
InitTree(&T);
CreateBiTree(&T,s);
if(T==NULL)
width=0;
else{
width=WidthBiTree(T);
}
printf("%d\n",width);
}
return 0;
}
我的代码调试之后就停在出队函数那里,电脑报错如下
求求大佬帮忙看看