计算二叉树最大的宽度(二叉树的最大宽度是指二叉树所有层中结点个数的最大值)。


计算二叉树最大的宽度(二叉树的最大宽度是指二叉树所有层中结点个数的最大值)。

正确答案:int Width(BiTree bt)//求二叉树bt的最大宽度 {if (bt==null) return (0); //空二叉树宽度为0 else {BiTree Q[];//Q是队列,元素为二叉树结点指针,容量足够大 front=1;rear=1;last=1; //front队头指针,rear队尾指针,last同层最右结点在队列中的位置 temp=0; maxw=0; //temp记局部宽度, maxw记最大宽度 Q[rear]=bt; //根结点入队列 while(front<=last) {p=Q[front++]; temp++; //同层元素数加1 if (p->lchild!=null) Q[++rear]=p->lchild; //左子女入队 if (p->rchild!=null) Q[++rear]=p->rchild; //右子女入队 if (front>last) //一层结束, {last=rear; if(temp>maxw) maxw=temp; //last指向下层最右元素, 更新当前最大宽度 temp=0; }//if }//while return (maxw); }//结束width


Tag:数据结构 宽度 结点 时间:2024-01-19 16:04:22

相关答案

热门答案