7-4 计算二叉树最大的宽度

根据带虚结点的先序序列建立二叉树,计算该二叉树最大的宽度(二叉树的最大宽度是指二叉树所有层中结点个数的最大值)并输出。

输入格式:

测试数据有多组,处理到文件尾。每组测试数据在一行中输入一个字符串(不含空格且长度不超过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;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

m0_74402833

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值