求二叉树的宽度,很常规。
只需要定一个last,指向每一层的最后一个点。
//2013年求高度,2019求宽度
//算法思想:①遍历 ②比较width
typedef struct BTNode{
int data;
struct BTNode *lchild;
struct BTNode *rchild;
}BTNode,*BiTree;
int width(BiTree T){
if(!T)
return 0;
BiTree Q[MAXSIZE],p;
int front=-1,rear=-1,width=1;
int last=0;
Q[++rear]=T;
while(front < rear){
if(p->lchild)
Q[++rear]=p->lchild;
if(p->rchild)
Q[++front]=p->rchild;
if(last=front){ //到了该层最后一个结点
if(rear-front>width){ // 比较当前宽度
width=rear-front; //若大于则更新
}
last=rear; //last指向该层最后一个结点
}
}
return width;
}