#define _crt_secure_no_warnings
#include
#include
//二叉樹結點
typedef
struct binarynode binarynode;
//遞迴求葉子數量
void
calculateleafnum
(binarynode* root,
int*leafnum)
if(root->lchild ==
null
&& root->rchild ==
null
)//判斷左子樹
calculateleafnum
(root->lchild,leafnum)
;//判斷右子樹
calculateleafnum
(root->rchild,leafnum);}
//遞迴求樹的高度
intcalculatetreedepth
(binarynode* root)
//深度初始化為0
int depth =0;
//分別求左右子樹的深度
int leftdepth =
calculatetreedepth
(root->lchild)
;int rightdepth =
calculatetreedepth
(root->rchild)
;//取二者中最大值,並加1(本層高度)
depth = leftdepth > rightdepth ? leftdepth +
1: rightdepth +1;
return depth;
}//建立二叉樹
void
createbinarytree()
; binarynode node2 =
; binarynode node3 =
; binarynode node4 =
; binarynode node5 =
; binarynode node6 =
; binarynode node7 =
; binarynode node8 =
;//建立結點關係
node1.lchild =
&node2;
node1.rchild =
&node6;
node2.rchild =
&node3;
node3.lchild =
&node4;
node3.rchild =
&node5;
node6.rchild =
&node7;
node7.lchild =
&node8;
//葉子數目
int leafnum =0;
//呼叫函式求葉子結點數目
calculateleafnum
(&node1,
&leafnum)
;printf
("leafnum = %d\n"
, leafnum)
;//計算樹的深度
int depth =
calculatetreedepth
(&node1)
;printf
("treedepth = %d\n"
, depth);}
intmain()
leafnum = 3
treedepth = 4
計算二叉樹葉子結點數目
二叉樹按照二叉鍊錶方式儲存,編寫程式,計算二叉樹中葉子結點的數目。按先序輸入二叉樹各結點,其中 表示取消建立子樹結點。輸出二叉樹中葉子節點的數目。abd eh cf i g include include include define datatype char using namespace st...
計算二叉樹葉子結點數目(耿6 14)
description 二叉樹按照二叉鍊錶方式儲存,編寫程式,計算二叉樹中葉子結點的數目。input 按先序輸入二叉樹各節點,其中 表示取消建立子樹結點。output 輸出二叉樹中葉子數目的結點 sample input abd eh cf i g sample output 4 include i...
求二叉樹的葉子節點數目
1.設定乙個輔助計數變數作為葉子數目 2.分別遞迴訪問左右子樹,當結點的左右子樹都為空時,計數變數加1 3.得到計數變數的值即為葉子數目 typedef struct binarynodebinarynode param int leafnum 傳入計數變數的位址,通過指標修改變數的值 leafnu...