C++ recursive solution


  • 1
    bool balanced( TreeNode* root, int& depth ) {
        if( !root ) return true;
        int left = 0, right = 0;
        if( balanced( root->left, left) && balanced( root->right, right ) ) {
            if( left - right >= -1 && left - right <= 1 ) {
                depth = 1 + max( left, right );
                return true;
            }
        }
        return false;
    }
    
    bool isBalanced(TreeNode* root) {
        int depth = 0;
        return balanced(root, depth );
    }

Log in to reply
 

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