求非空二叉树的宽度

考研题目
即求最宽的那层有几个节点
用层次遍历 看每一层的节点数,如果大于最大的节点数(开始假定为0),那么就替换。
根据王道上的本来求树高度,加了count 求宽度,去了count就还是求高度了

int width(BiTree T){
	int front=-1,rear=-1;
	int level=0,last=0;//last是当前层最后一个节点;
	int count =0,max=0;
	BiTree Q[maxsize];
	BiNode *p;
	Q[rear++]=T;
	while(front<rear){ //队列不空
		p=Q[front++];//出队 找它儿子
		if(p->lchild)
			Q[rear++]=p->lchild;//左儿子进来
			count++; //这层多一个节点
		if(p->rchild)
			Q[rear++]=p->rchild;//右儿子进来
			count++;//这层多一个节点
		if(front==last){//这一层结束了
			last=rear; //下一层的最后一个节点
			if(max<count)
				max=count;//记录最宽的一层
		}//if
	}//while
}
发布了3 篇原创文章 · 获赞 0 · 访问量 23

猜你喜欢

转载自blog.csdn.net/qq_43251362/article/details/104825394