国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C++ > 正文

C語言中計算二叉樹的寬度的兩種方式

2020-05-23 13:47:49
字體:
供稿:網(wǎng)友

C語言中計算二叉樹的寬度的兩種方式

二叉樹作為一種很特殊的數(shù)據(jù)結(jié)構(gòu),功能上有很大的作用!今天就來看看怎么計算一個二叉樹的最大的寬度吧。

采用遞歸方式

下面是代碼內(nèi)容:

int GetMaxWidth(BinaryTree pointer){  int width[10];//加入這棵樹的最大高度不超過10  int maxWidth=0;  int floor=1;  if(pointer){    if(floor==1){//如果訪問的是根節(jié)點的話,第一層節(jié)點++;      width[floor]++;      floor++;      if(pointer->leftChild)        width[floor]++;      if(pointer->rightChild)        width[floor]++;    }else{      floor++;      if(pointer->leftChild)        width[floor]++;      if(pointer->rightChild)        width[floor]++;    }    if(maxWidth<width[floor])      maxWidth=width[floor];    GetMaxWidth(pointer->leftChild);    floor--;//記得退回一層,否則會出錯。因為已經(jīng)Get過了,所以要及時的返回。    GetMaxWidth(pointer->rightChild);  }  return maxWidth;}

采用非遞歸方式

采用非遞歸方式計算二叉樹的寬度需要借助于隊列。代碼如下:

int GetMaxWidth(BinaryTree pointer){  if(pointer==null){    return 0;  }  Queue<BinaryTreeNode> queue=new ArrayDeque<BinaryTreeNode>();  int maxWidth=1;//最大寬度  queue.add(pointer);  while(true){    int size=queue.size();//計算當(dāng)前層的節(jié)點的個數(shù)    if(size==0){      break;    }    while(size>0){//如果當(dāng)前層還有節(jié)點就進行下去      BinaryTreeNode node=queue.poll();      size--;      if(node->leftChild)        queue.add(node->leftChild);//當(dāng)前節(jié)點的左子樹入隊      if(node->rightChild)        queue.add(node->rightChild);//當(dāng)前節(jié)點的右子樹入隊      maxWidth=Math.max(size,queue.size());    }  }  return maxWidth;//返回計算所得的最大的二叉樹的寬度。}

總結(jié):

不管采用哪種方式,實際上還是利用了對二叉樹的遍歷的特點來進行的。

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!


發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 固阳县| 伊吾县| 利津县| 马边| 婺源县| 登封市| 靖宇县| 平乡县| 黔西县| 界首市| 萨迦县| 承德市| 涡阳县| 周口市| 平塘县| 台中县| 阿拉善右旗| 京山县| 日土县| 肇庆市| 抚州市| 五大连池市| 天台县| 高陵县| 页游| 耒阳市| 塔河县| 万山特区| 吉木乃县| 禹城市| 古蔺县| 班玛县| 嵊州市| 梁山县| 利津县| 博客| 乐陵市| 江油市| 双柏县| 赤峰市| 潞城市|