求二叉树的宽度
//二叉树结构 typedef char TElemType; typedef struct BiTNode { TElemType data; struct BiTNode *lchild, *rchild; }BiTNode, *BiTree; //链队 typedef struct QNode_BT { BiTNode* data; struct QNode_BT *next; }QNode_BT, *QNode_BTPtr; typedef struct { QNode_BTPtr front,rear; }LinkQueue_BT; Status InitQueue(LinkQueue_BT &Q) { Q.front = Q.rear = new QNode_BT; Q.front->next = nullptr; return OK; } Status EnQueue(LinkQueue_BT &Q, BiTNode* e) { QNode_BT *p = new QNode_BT; p->data = e; p->next = nullptr; Q.rear->next = p; Q.rear = p; return OK; } Status DeQueue(LinkQueue_BT &Q, BiTNode* &e) { if (Q.front == Q.rear) return ERROR; QNode_BT* p = Q.front->next; e = p->data; Q.front->next = p->next; if (Q.rear == p) Q.rear = Q.front; delete p; return OK; } bool QueueIsEmpty(LinkQueue_BT Q) { return Q.front == Q.rear ? true : false; } int BiTreeMaxWidth(BiTree T) { int MaxWidth = 0;//最大宽度 int NextWidth = 0;//下一层宽度 int CurrentWidth = 0;//当前层宽度 LinkQueue_BT Q; BiTNode* p; InitQueue(Q); if (T) { EnQueue(Q,T); CurrentWidth = 1; NextWidth = 0; MaxWidth = CurrentWidth; } while(!QueueIsEmpty(Q)) { DeQueue(Q, p); if ( p->lchild ) { EnQueue(Q, p->lchild); NextWidth++;//累计当前下一个层的节点数 } if ( p->rchild ) { EnQueue(Q, p->rchild); NextWidth++;//累计当前下一个层的节点数 } MaxWidth = MaxWidth > NextWidth ? MaxWidth : NextWidth;//获取最大层次 if (--CurrentWidth == 0) {//如果当前层的所有结点都已出队,则开始统计下一层宽度 CurrentWidth = NextWidth; NextWidth = 0; } } return MaxWidth; }
作者:hellototoro
出处:https://www.cnblogs.com/hellototoro/
版权:本文版权归作者和博客园共有。
转载:欢迎转载,请保留此段。

浙公网安备 33010602011771号