C++ HOJ 求解二叉树的宽度(队列实现)

来源:互联网 发布:淘宝文胸买家秀 编辑:程序博客网 时间:2024/05/18 16:13

【摘要】

我们可以把二叉树中每层的节点依次放入一个队列中。设置一个变量width用于存储树的宽度。每一层的节点入队时计算该层节点的数目,如果该层次节点的数目大于width的值,那么把该层次节点的数目赋给width.如此,对二叉树按层遍历一遍之后width中保存的就是该二叉树的宽度。

【算法思想】

队列实现层次遍历,找到下一层的子节点入队,子节点一次遍历保证一次单层测宽,最终获取树宽。

【源码实现】

int WidthOfTheTree(Node* pRoot)  {      if(pRoot==NULL)          return 0;      queue<Node*> MyQueue2;      MyQueue2.push(pRoot);      int width=1;      int curwidth=1;      int nextwidth=0;      while(!MyQueue2.empty())      {          while(curwidth!=0)          {              Node* pTmp=MyQueue2.front();              MyQueue2.pop();              curwidth--;              if(pTmp->pLeft!=NULL)              {                  MyQueue2.push(pTmp->pLeft);                  nextwidth++;              }              if (pTmp->pRight!=NULL)              {                  MyQueue2.push(pTmp->pRight);                  nextwidth++;              }          }          if(nextwidth>width)              width=nextwidth;          curwidth=nextwidth;          nextwidth=0;      }      return width;  }  

0 0
原创粉丝点击