Integer MAX and MIN test cases


  • 0
    J

    Did someone encounter the test cases where Integer.MAX_VALUE appears?

    For example, the input is [2174XXXXXX] (sth like that, a big number indicating max integer), the expected answer is true my output is false.

    Can someone explain why we have test cases for MAX and MIN? Is it really NECESSARY?

    Thank you all!


  • 0
    L

    Those are corner cases to check how you manage the first value's comparison if you use such code below. If you are traverse it from right to left then int.MaxValue case will make more sense.

    public bool IsValidBST(TreeNode root) {
        Stack<TreeNode> stack = new Stack<TreeNode>();
        long last = (long)int.MinValue - 1;
        while(root != null || stack.Count != 0)
            if(root != null)
            {
                stack.Push(root);
                root = root.left;
            }
            else
            {
                root = stack.Pop();
                if(last >= (long)root.val) return false;
                last = root.val;
                root = root.right;
            }
        return true;
    }

  • -1
    N
    public bool IsValidBST(TreeNode root) {
        boolean isFirstNode = true;
        int pre = 0;
        Stack<TreeNode> stack = new Stack<TreeNode>();
        TreeNode tmp = root;
        while(tmp != null || !stack.isEmpty()){
            while(tmp != null){
                stack.push(tmp);
                tmp = tmp.left;
            }
            tmp = stack.pop();
            if(isFirstNode)
                isFirstNode = false;
            else if(pre >= tmp.val)
                return false;
            pre = tmp.val;
            tmp = tmp.right;
        }
        return true;
    }

  • 1
    Y
    bool check(struct TreeNode* root, long min, long max) {
        return root->val > min && root->val < max &&
            (root->left ? check(root->left, min, root->val) : true) &&
            (root->right ? check(root->right, root->val, max) : true) ;
    }
    bool isValidBST(struct TreeNode* root) {
        if (root == NULL)
            return true;
        return check(root, INT_MIN - 1L, INT_MAX + 1L);
    }
    

    Just use long as your parameters' type, and pass INT_MIN - 1L as the initial value


Log in to reply
 

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