代码如下
#include<stdio.h> #include<stdlib.h> #define Max_Size 50 typedef struct bitree { char data; int level; struct bitree *lchild; struct bitree *rchild; }BiTreeNode,*BiTree; typedef struct queue { BiTree Data[Max_Size]; int front; int rear; }SqQueue; void init_queue(SqQueue *); void EnQueue(SqQueue *,BiTree); void DeQueue(SqQueue *); int empty_queue(SqQueue *); BiTree init_bitree(); void travel_bitree(BiTree); void level_set(BiTree); void max_wideth(SqQueue); int main() { BiTree T; T=init_bitree();//CEI#J##F#GK##H##D## T->level=1; level_set(T); printf("层次遍历结果如下:\n"); travel_bitree(T); return 0; } void init_queue(SqQueue *Q) { Q->front=Q->rear=0; } void EnQueue(SqQueue *Q,BiTree e) { if(e) { Q->Data[Q->rear]=e; Q->rear++; } } void DeQueue(SqQueue *Q) { Q->front++; } int empty_queue(SqQueue *Q) { if(Q->front==Q->rear) return 1; else return 0; } BiTree init_bitree() { char ch; ch=getchar(); if(ch=='#') return NULL; else { BiTree T; T=(BiTree )malloc(sizeof(BiTreeNode)); T->data=ch; T->lchild=init_bitree(); T->rchild=init_bitree(); return T; } } void level_set(BiTree T) { if(T->lchild) { T->lchild->level=T->level+1; level_set(T->lchild); } if(T->rchild) { T->rchild->level=T->level+1; level_set(T->rchild); } } void travel_bitree(BiTree T) { SqQueue Q;//层次遍历二叉树 init_queue(&Q); EnQueue(&Q,T); while(!empty_queue(&Q)) { EnQueue(&Q,Q.Data[Q.front]->lchild); EnQueue(&Q,Q.Data[Q.front]->rchild); printf("(结点:%c 层次:%d)\n",Q.Data[Q.front]->data,Q.Data[Q.front]->level); DeQueue(&Q); } max_wideth(Q); } void max_wideth(SqQueue Q) { int num[Max_Size+1]; int max=0; for(int i=1;i<=Max_Size;i++) num[i]=0; for(int i=0;i<Q.rear;i++) { num[Q.Data[i]->level]++; } for(int i=1;i<=Max_Size;i++) { if(max<num[i]) { max=num[i]; } } printf("该二叉树的最大宽度为:%d",max); }
标签:遍历,level,int,BiTree,SqQueue,C语言,二叉树,bitree,void From: https://www.cnblogs.com/wei-1024/p/17908340.html