平衡二叉树(Balanced Binary Tree)又被称为AVL树(有别于AVL算法),且具有以下性质:它是一 棵空树或它的左右两个子树的高度差的绝对值不超过1,并且左右两个子树都是一棵平衡二叉树。
//获取树的高度
int maxDepth(struct TreeNode* root){
if(root == NULL)
return 0;
int l = maxDepth(root->left);
int r = maxDepth(root->right);
return l > r ? l + 1 : r + 1;
}
//判断是否为平衡二叉树
bool isBalanced(struct TreeNode* root){
if(root == NULL)
return true;
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return abs(left - right) < 2 && isBalanced(root->left) && isBalanced(root->right);
}