统计利用先序遍历创建的二叉树的宽度

方案一:递归实现
通过设置一个计数数组,记录每一层的结点数

#include <iostream>
#include <stdlib.h>
using namespace std;
typedef struct BiNode
{
    char data;
    BiNode *lchild,*rchild;

}BiNode,*BiTree;
int count[1000]={0},Max=0;//count记录每层的节点数,Max记录宽度
BiTree CreatBiTree()//先序遍历创建二叉树
{
    BiTree T;
    char ch;
    cin>>ch;
    if(ch=='#')
        T=NULL;
    else
    {
        T=(BiTree)malloc(sizeof(BiNode));
        T->data=ch;
        T->lchild=CreatBiTree();
        T->rchild=CreatBiTree();
    }
    return T;
}
void getnum(BiTree T,int i)
{
    if(T!=NULL)
    {
        count[i]++;//第i层结点数+1
        if(count[i]>Max)Max=count[i];
        getnum(T->lchild,i+1);//T的左孩子,层数+1
        getnum(T->rchild,i+1);//T的右孩子,层数+1
    }
}
int main()
{
    BiTree T;
    T=CreatBiTree();
    getnum(T,1);
    cout<<Max;
    return 0;
}

方案二:
层次遍历,队列实现

#include <iostream>
#include <algorithm>
#include <queue>
#include <stdlib.h>
using namespace std;
typedef struct node
{
    char dada;
    node *lchild,*rchild;
}BiNode,*BiTree;
BiTree CreatBiTree()
{
    char ch;BiTree T;
    cin>>ch;
    if(ch=='#') T=NULL;
    else
    {
        T=(BiTree)malloc(sizeof(BiNode));
        T->dada=ch;
        T->lchild=CreatBiTree();
        T->rchild=CreatBiTree();
    }
    return T;
}
int Max=0;
void GetNum(BiTree T)
{
    if(T!=NULL)
    {
        queue<BiTree>q;
        q.push(T);

        while(1)
        {
            int len=q.size();//当前遍历层的宽度
            if(len>Max)Max=len;//Max记录最大宽度(树的宽度)
            if(len==0) break;
            while(len--)//当前层遍历结束后,队列的长度为下一层的宽度
            {
                BiTree now;
                now=q.front();
                q.pop();
                if(now->lchild!=NULL)
                    q.push(now->lchild);
                if(now->rchild!=NULL)
                    q.push(now->rchild);
            }
        }
    }
}
int main()
{
    BiTree T=CreatBiTree();
    GetNum(T);
    cout<<Max;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值