思路:
设置一个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;
}