//求二叉樹的高度
int Depth(BTree bt) {
int hl, hr; //定義左右數的高度
if (bt == NULL) //bt為空樹,高度為0
return 0;
else //bt為非空
{
hl = Depth(bt->lchild); //求左子樹的高度
hr = Depth(bt->rchild); //求右子樹的高度
if (hl > hr) return (hl + 1);
else
return (hr + 1);
}
}
int hl,hr沒有初始化,默認初始值為0,每遞回一次節點hl、hr就加1,這是為啥
uj5u.com熱心網友回復:
int GetHeight(BinTree BT){
int h1;
int h2;
if(!BT)
return 0;
else{
h1 = GetHeight(BT->left);
h2 = GetHeight(BT->right);
return h1>h2?++h1:++h2;
}
}
uj5u.com熱心網友回復:
每次遞回的hr hl 屬于不同的函式uj5u.com熱心網友回復:
加上父節點,之前沒加上父節點,現在就+1uj5u.com熱心網友回復:
我常說要理解遞回,一個是縮小資料規模,以最小的輸入理解遞回再擴大輸入規模,不要拘泥于具體的資料,而是超脫于資料來看演算法
比如你的資料
nt Depth(BTree bt) {
int hl, hr; //定義左右數的高度
if (bt == NULL) //bt為空樹,高度為0
return 0;
else //bt為非空
{
hl = Depth(bt->lchild); //求左子樹的高度 這里的hl指的是左樹的高度,而不管它如何求出左樹的高度
hr = Depth(bt->rchild); //求右子樹的高度 右樹同上。
if (hl > hr) return (hl + 1);
else
return (hr + 1);
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/88728.html
標籤:新手樂園
下一篇:C++ if陳述句求解惑
