递归解法:
(1)如果二叉树为空,返回真
(2)如果二叉树不为空,如果左子树和右子树都是AVL树,且左子树和右子树高度相差不大于1,返回真,其他返回假
bool IsAVL(BinaryTreeNode *pRoot, int &height)
{
if (pRoot == NULL) {
height = 0;
return true;
}
int heightLeft;
bool resultLeft = IsAVL(pRoot->lchild, heightLeft);
int heightRight;
bool resultRight = IsAVL(pRoot->rchild, heightRight);
// 左子树和右子树都是AVL,并且高度相差不大于1,返回真
if (resultLeft && resultRight && abs(heightLeft - heightRight) <= 1) {
height = max(heightLeft, heightRight) + 1;
return true;
}
else {
height = max(heightLeft, heightRight) + 1;
return false;
}
}