bool isBalanced(TreeNode* root) {
if(!root) return true;
if(abs(getDept(root->left)-getDept(root->right))>1) return false;
return isBalanced(root->left)&&isBalanced(root->right);
}
int getDept(TreeNode* root){
if(!root) return 0;
return 1+max(getDept(root->left),getDept(root->right));
}
bool isBalanced(TreeNode* root) {
if(checkDept(root)==-1) return false;
return true;
}
int checkDept(TreeNode* root){
if(!root) return 0;
int left=checkDept(root->left);
if(left==-1) return -1;
int right=checkDept(root->right);
if(right==-1)
return -1;
if(abs(left-right)>1) return -1;
else return 1+max(left,right);
}
平衡树维基百科
平衡树百度百科
平衡树博客