方案一:递归实现
通过设置一个计数数组,记录每一层的结点数
#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;
}