Code is wrong when input [0], why?


  • 0
    X
    #define MAX 2147483647
    #define MIN -2147483648
     
    bool isValid(struct TreeNode *root, long min, long max)
    {
        return root->val > min 
            && root->val < max 
            && (root->left?isValid(root->left, min, root->val):true) 
            && (root->right?isValid(root->right, root->val, max):true);    
        
    }
    
    bool isValidBST(struct TreeNode* root) {
        if(!root)
            return true;
        
        return isValid(root, MIN-1, MAX+1);
    }
    

    info output:

    Input:	[0]
    Output:	false
    Expected:	true

  • 0
    T

    for this case ,be careful to
    LONG_MIN Minimum value for an object of type long int -2147483647 (-231+1) or less*
    LONG_MAX Maximum value for an object of type long int 2147483647 (231-1) or greater*

    so
    return isValid(root, MIN-1, MAX+1);

    to
    return isValid(root, MIN+1, MAX);


Log in to reply
 

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