c语言二叉树宽度

题目:假设二叉树采用二叉链表存储结构,设计一个算法,求非空二叉树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;
}

结果:

  • 10
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值