10ms accepted c solution by calculating depth recursively


  • 0
    P

    bool isBalanced(struct TreeNode* root) {

    if(root == NULL)
    return true;

    int right, left;

    right = depth(root->right);
    left = depth(root->left);
    
    if(right!=left && right!=(left-1) && left!=(right-1))
    return false;
    
    if(!isBalanced(root->right) || !isBalanced(root->left))
    return false;
    
    return true;
    

    }
    int depth(struct TreeNode* root)
    {
    if(root == NULL)
    return 0;

    return 1 + max(depth(root->left), depth(root->right));
    

    }
    int max(int a, int b)
    {
    return a>b?a:b;
    }


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.