通过层次遍历计算二叉树的宽度;
int Broad(BiTree T)
{
if (T)
{
BiTree p=NULL;
queue<BiTree> Q;
Q.push(T);
int max = 0;
while (!Q.empty())
{
int curwidth = Q.size();//当前层节点数
for (int i = 0; i < curwidth; i++)//为计算下一层节点数(宽度)做准备
{
p = Q.front();
Q.pop();
if (p->lchild)
Q.push(p->lchild);
if (p->rchild)
Q.push(p->rchild);
}
max = max > curwidth ? max : curwidth;//更新二叉树宽度
}
return max;
}
return 0;
}