考研进行时——二叉树的层次遍历和计算二叉树的宽度
/**********************
先序建立二叉树;
利用C++中的队列实现二叉树的层次遍历;
Width()函数返回二叉树的宽度
*************************************************/
#include<iostream>
#include<queue>
#include<stdio.h>
#include<stdlib.h>
using namespace std;
typedef char ElemType;
typedef struct BT
{
ElemType data;
struct BT *lch,*rch;
}BT,*BN;
BT * CreateBT()
{
BT *t;
char c;
scanf("%c",&c);
if(c=='#')t=NULL;
else
{
t=(BT*)malloc(sizeof(BT));
t->data=c;
t->lch=CreateBT();
t->rch=CreateBT();
}
return t;
}
void traverse(BN T)
{
queue<BN> q;
BN p=NULL;
if(T)
q.push(T);
while(!q.empty())
{
p=q.front();
q.pop();
cout<<p->data<<" ";
if(p->lch)
{
q.push(p->lch);
}
if(p->rch)
{
q.push(p->rch);
}
}
}
int Width(BT *T)
{
if(T!=NULL)
{
if(T->lch==NULL&&T->rch==NULL)
return 1;
else
return Width(T->lch)+Width(T->rch);
}
}
int main()
{
BT *T=NULL;
printf("请输入要创建的树:");
T=CreateBT();
printf("\n层次遍历序列:\n");
traverse(T);
printf("\n树的宽度是: ");
printf("%d",Width(T));
return 0;
}
树的原型是: