思路:
設置一個balance標記(0表示平衡,1表示不平衡)
設置高度height(用於判斷平衡的標準)
1.若樹爲空 ,高度爲0,balance爲1
2.若樹無左右子,高度爲1,baance爲1
3.出去以上兩種遞歸出口,剩下的就需要左右樹分別遞歸,遞歸的過程和返回的過程如下圖所示:
左右子樹分別設置自己的height和balance。
樹的高度爲左右子樹高度的最大值加1
如果左右子樹高度差小於2,繼續判斷左右子樹是否平衡,只有左右子樹都平衡,樹才平衡
若左右子樹高度差大於等於2,直接可以判斷不平衡
void check_ALV(BiTree T,int& balance, int& height) {
int L_balance = 0, R_balance = 0, L_height = 0, R_height = 0;
if (T == NULL) {
height = 0;
balance = 1;
}
else if (T->lchild == NULL && T->rchild == NULL) {
height = 1;
balance = 1;
}
else {
check_ALV(T->lchild, L_balance, L_height);
check_ALV(T->lchild, R_balance, R_height);
height=max(L_height,R_height)+1;
if (abs(L_height - R_height) < 2) balance = L_balance && R_balance;
else balance = 0;
}
}
void eight_4_5(BiTree T) {
int balance = 0;
int height = 0;
check_ALV(T, balance, height);
cout << "樹的高度爲:" << height << endl;
cout << "樹是否平衡?" << balance << endl;
}