C++ 12ms optimal solution.


  • 2
    int height(TreeNode* root){
        if (root==NULL) return 0;
        int l=height(root->left),r=height(root->right);
        if (l==-1 || r==-1 || l>r+1 || r>l+1) return -1;
        else{
            return max(l,r)+1;
        }
    }
    
    bool isBalanced(TreeNode* root) {
        return height(root)!=-1;
        
    }

Log in to reply
 

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