以此树为例:
求解二叉树宽度
主要采用层次遍历的思想,每遍历一层,记录一层的宽度,最后取宽度最大值
int getMaxWidth(BiTree* T) {
if (T == NULL)
{
return 0;
}
//层次遍历队列
BiTree* Q[100];
//记录宽度
int width = 1, temp = 0;
//队列头尾指针
int front = -1, rear = -1;
//记录每一层结束的标记
int last = 0;
BiTree* p;
Q[++rear] = T;
while (front < rear)
{
p = Q[++front];
temp++;
if (p->lchild != NULL) Q[++rear] = p->lchild;
if (p->rchild != NULL) Q[++rear] = p->rchild;
//front == last 表示当前层宽度计算完毕,可以进行比较了
if (front == last)
{
if (temp > width) width = temp;
temp = 0;
last = rear;
}
}
return width;
}
结果展示
cout << "树的宽度为:" << getMaxWidth(T) << endl;