計算二叉樹的寬度的兩種方式
阿新 • • 發佈:2019-01-27
作用 出錯 sub 當前 我們 教程 tps inter 利用
二叉樹作為一種很特殊的數據結構,功能上有很大的作用!今天就來看看怎麽計算一個二叉樹的最大的寬度吧。
采用遞歸方式
下面是代碼內容:
int GetMaxWidth(BinaryTree pointer){
int width[10];//加入這棵樹的最大高度不超過10
int maxWidth=0;
int floor=1;
if(pointer){
if(floor==1){//如果訪問的是根節點的話,第一層節點++;
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--;//記得退回一層,否則會出錯。因為已經Get過了,所以要及時的返回。
GetMaxWidth(pointer->rightChild);
}
return maxWidth;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
采用非遞歸方式
采用非遞歸方式計算二叉樹的寬度需要借助於隊列。代碼如下:
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();//計算當前層的節點的個數
if(size==0){
break;
}
while(size>0){//如果當前層還有節點就進行下去
BinaryTreeNode node=queue.poll();
size--;
if(node->leftChild)
queue.add(node->leftChild);//當前節點的左子樹入隊
if(node->rightChild)
queue.add(node->rightChild);//當前節點的右子樹入隊
maxWidth=Math.max(size,queue.size());
}
}
return maxWidth;//返回計算所得的最大的二叉樹的寬度。
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
總結:
不管采用哪種方式,實際上還是利用了對二叉樹的遍歷的特點來進行的。
再分享一下我老師大神的人工智能教程吧。零基礎!通俗易懂!風趣幽默!還帶黃段子!希望你也加入到我們人工智能的隊伍中來!https://blog.csdn.net/jiangjunshow
計算二叉樹的寬度的兩種方式