题目:假设二叉树采用二叉链表存储结构,设计一个算法,求非空二叉树b的宽度(即具有结点数最多的那一层的结点的个数)
思路:结合层次遍历和利用层次遍历求二叉树的高度的思路做,用变量i记录每层结点的个数,max记录最大值,其实就是在二叉树高度代码功能函数中的循环里增加一个i变量记录结点个数。
样例图:
代码:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
//二叉树
typedef struct bitree {
char data;
struct bitree* lchild, * rchild;
}bitree;
//队列
typedef struct {
bitree* data[50];
int front, rear;
}sequeue;
//创建二叉树
bitree* create(bitree* t) {
char ch;
scanf("%c", &ch);
if (ch == '#') {
return NULL;
}
else {
t = (bitree*)malloc(sizeof(bitree));
t->data = ch;
t->lchild=create(t->lchild); //返回的指针必须接收,否则访问指针时,可能会因为未初始化导致异常
t->rchild=create(t->rchild);
return t;
}
}
//宽度函数
int width(bitree* t) {
if (t == NULL) {
return 0;
}
int last = 0, level = 0, max = 1, i = 0;//最右层的结点,level记录高度
sequeue s;
s.front = s.rear = 0;
bitree* p = t;
s.data[(s.rear)++] = p; //根节点入队
while (s.front != s.rear) {
i++;
p = s.data[(s.front)++];
if (p->lchild != NULL) {
s.data[(s.rear)++] = p->lchild;
}
if (p->rchild != NULL) {
s.data[(s.rear)++] = p->rchild;
}
if (last == s.front - 1) { //这里减一是因为,front是在赋值结束之后会才会自增,所以-1
last = s.rear - 1; //last记录下一层的最后一个结点的下标
if (i > max) {
max = i;
i = 0; //记录下一层结点时,i要归零。
}
}
}
return max;
}
int main() {
bitree* t = NULL;
t = create(t);
int max = width(t);
printf("最大宽度为%d",max);
return 0;
}
结果: