#include<stdio.h>
#include<iostream>
#include<stdlib.h>
using namespace std;
#define MAXSIZE 100
typedef struct bnode
{
char data;
struct bnode *lchild,*rchild;
}BNode,*bitree;
bitree create()
{
bitree bt=NULL;
char ch;
scanf("%c",&ch);
if(ch==' ')
return NULL;
bt=new BNode;
bt->data=ch;
bt->lchild=create();
bt->rchild=create();
}
void level(bitree bt)
{
bitree q[MAXSIZE];
int f,r;
f=r=0;
int i,j;
if(bt)
{
r++;
q[r]=bt;
while(f!=r)
{
f++;
bitree p=q[f];
cout<<p->data<<" ";
if(p->lchild)
{
r++;
q[r]=p->lchild;
}
if(p->rchild)
{
r++;
q[r]=p->rchild;
}
}
}
}
int width(bitree bt)
{
int wid=0;
int i,j;
bitree q[MAXSIZE];
int f,r;
f=r=0;
if(bt)
{
r++;
q[r]=bt;
while(f!=r)
{
int len=abs(f-r);
if(len>wid)
wid=len;
for(i=0;i<len;i++)
{
f++;
bitree p=q[f];
if(p->lchild)
{
r++;
q[r]=p->lchild;
}
if(p->rchild)
{
r++;
q[r]=p->rchild;
}
}
}
cout<<"wid"<<wid<<endl;
return wid;
}
}
int main()
{
bitree bt;
bt=create();
level(bt);
cout<<endl;
cout<<width(bt);
}
复习二叉树层次遍历和求树的宽度
最新推荐文章于 2024-10-05 18:47:59 发布