递归读取深度,再判断。
int getDepth(struct TreeNode *root) {
int left, right = 0;
if (root == NULL)
return 0;
else{
left = getDepth(root->left)+1;
right = getDepth(root->right)+1;
}
return left > right ? left : right;
}
bool isBalanced(struct TreeNode *root){
if(root == NULL) return true;
int l_depth = getDepth(root -> left);
int r_depth = getDepth(root -> right);
if(abs(l_depth - r_depth) > 1) return false;
return isBalanced(root -> left) && isBalanced(root -> right);
}