假设二叉树采用二叉链表存储结构,设计一个算法,求非空二叉树b的宽度(即具有结点数最多的那一层的结点个数)--可执行代码

代码思路:利用队列找出每一层的末尾,当f=末尾时,判断当前层结点个数。

#include<iostream>
using namespace std;

typedef struct TreeNode
{
    char data;
    TreeNode*lchild,*rchild;
}TreeNode,*tree;

void build(tree &t){
    char x;
    x=getchar();
    if(x=='#')t=NULL;
    else{
        t=(TreeNode*)malloc(sizeof(TreeNode));
        t->data=x;
        t->lchild=NULL;
        t->rchild=NULL;
        build(t->lchild);
        build(t->rchild);
    }
}//建树

int search(tree t){
    int ans=0,L=0;//ans为层数,L为每一层最后一个结点的位置。
    int max=0,num=1;
    tree queue[20];//定义一个树队列
    int f=-1;int r=-1;//入队:r,出队:f
    TreeNode* p;//工作指针
    queue[++r]=t;//头节点入队
    while(f<r){//队列不空则一直循环
        p=queue[++f];
        if(p->lchild) queue[++r]=p->lchild;
        if(p->rchild) queue[++r]=p->rchild;
        if(f==L){
            L=r;
            ans++;
            if(num>max){
                max=num;
            }
            num=1;
        }
        else{
            num++;
        }

    }
    return max;
}
int main(){
    int max;
    tree t;
    build(t);
    max=search(t);
    cout<<max<<" ";
    
}

输入:ABD##E##CF##G##

输出:4

  • 11
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值