代码思路:利用队列找出每一层的末尾,当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