Why this is failed


  • 0
    K
    bool isValidBST(TreeNode *root) {
        static TreeNode *pre = NULL;
        if (!root) return true;
        if (!isValidBST(root->left)) return false;
        if (pre && root->val <= pre->val) return false;
        pre = root;
        return isValidBST(root->right);
    }
    

    The test case {0,-1} failed. But I tested with my gcc, it is working fine.

    Btw, I guess the tree is like:

        0
       /
    -1
    

    Right?


  • 4
    K

    Ok, I found why this is happening: the function is not reentrant safe. i.e. if run two test cases, first will success and the second one will fail.

    By changing the static variable as a class member the problem fixed.


Log in to reply
 

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