My C++ code in 9ms


  • 0
    P
    bool isBalanced(TreeNode* root) {
        int length = 0 ;
        return Balanced(root, length);
    }
    
    bool Balanced(TreeNode* root, int &length){
        if(!root){
            length = 0;
            return true;
        }
        int llength = 0, rlength = 0;
        bool lstatus = Balanced(root->left, llength);
        bool rstatus = Balanced(root->right, rlength);
        length = 1 + max(llength, rlength);
        if(!lstatus || !rstatus || abs(llength - rlength) > 1)
            return false;
        return true;
    }

Log in to reply
 

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