https://leetcode.cn/problems/balanced-binary-tree/description/
The idea of dividing this question into sub-problems is to calculate the height of the left and right subtrees and then subtract them to see if they are greater than 1, so the code is as follows
int _isBalanced(struct TreeNode* root)
{
if(root == NULL)
{
return 0;
}
int leftdepth = _isBalanced(root->left);
int rightdepth = _isBalanced(root->right);
return leftdepth > rightdepth ? leftdepth+1 : rightdepth+1;
}
bool isBalanced(struct TreeNode* root) {
if(root == NULL)
{
return true;
}
int ret = abs(_isBalanced(root->left) - _isBalanced(root->right));
if(ret > 1)
{
return false;
}
return isBalanced(root->left) && isBalanced(root->right);
}
——————————Water article————————————————————