根据带虚结点的先序序列建立二叉树,计算该二叉树最大的宽度(二叉树的最大宽度是指二叉树所有层中结点个数的最大值)并输出。
输入格式:
测试数据有多组,处理到文件尾。每组测试数据在一行中输入一个字符串(不含空格且长度不超过80),表示二叉树的先序遍历序列,其中字符*
表示虚结点(对应的子树为空)。
输出格式:
对于每组测试,输出二叉树的最大宽度。输出格式为:“maxWidth: max”,其中max为二叉树的最大宽度值。
输入样例:
HDA**C*B**GF*E***
-+a**xb**-c**d**/e**f**
输出样例:
maxWidth: 3
maxWidth: 4
代码长度限制
16 KB
时间限制
400 ms
内存限制
64 MB
#include<stdio.h>
#include<stdlib.h>
typedef struct Binode{
char data;
struct Binode*lchild,*rchild;
}BiNode,*Bitree;
char temp[1000];//用来记录输入的字符串
int j=-1;
int counttree=0;//记录树的个数
//创建树
Bitree creattree(){
char ch=temp[++j];
if(ch=='*'){
return NULL;
}
Bitree bt=(Bitree)malloc(sizeof(BiNode));
bt->data=ch;
bt->lchild=creattree();
bt->rchild=creattree();
return bt;
}
//将输入的字符串储存在temp数组中
void getstr(){
int i=0;
char ch;
while(scanf("%c",&ch)!=-1){
if(ch!='\n'){
temp[i++]=ch;
}else{
counttree++;//当换行时二叉树的个数加一
}
}
}
//通过广度优先搜索树的最大宽度
int max_width(Bitree bt){
if (bt == NULL) {
return 0;//根节点如果是空的,二叉树最大宽度是0
}
//利用队列进行计算最大宽度
BiNode* queue[80];
int front = 0, rear = 0;
queue[rear++] = bt;//先将根节点入队
int maxWidth = 0;
while (front < rear) {
int currentWidth = rear - front;//计算当前层的全部节点数量(即宽度)
if (currentWidth > maxWidth) {
maxWidth = currentWidth;
}
for (int i = 0; i < currentWidth; i++) {
BiNode* node = queue[front++];//上一层的节点出队
//上一层的节点的左右孩子们全部入队
if (node->lchild != NULL) {
queue[rear++] = node->lchild;
}
if (node->rchild != NULL) {
queue[rear++] = node->rchild;
}
}
}
return maxWidth;
}
int main(){
getstr();
Bitree bt[counttree];
for(int i=0;i<=counttree;i++){
bt[i]=creattree();
if(i==counttree){
printf("maxWidth: %d",max_width(bt[i]));
}else{
printf("maxWidth: %d\n",max_width(bt[i]));
}
}
return 0;
}