leetcode (balanced binary tree)

Insert image description here
https://leetcode.cn/problems/balanced-binary-tree/description/

Insert image description here
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————————————————————
Insert image description here

Guess you like

Origin blog.csdn.net/2301_76895050/article/details/134978187