C++, O(n)-time, Short Code


  • 0
    bool isBalanced(TreeNode* root) {
        return (height(root) != -1);
    }
    int height(TreeNode* root) {
        if (!root) return 0;
        int leftH, rightH;
        if ((leftH = height(root->left)) == -1) return -1;
        if ((rightH = height(root->right)) == -1 || abs(leftH - rightH) > 1) return -1;
        return 1 + max(leftH, rightH);
    }
    

Log in to reply
 

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