What's wrong with my code? Could anyone help me?


  • 0
    B

    My code runs properly under vs 2013 and g++ 4.8.2, but it always get a wrong result in leetcode.

    bool isValidBST(struct TreeNode *root) {
        static signed int v = INT_MIN;
    	if (!root) return true;
    	if (!isValidBST(root->left)) return false;
    	if (root->val <= v) return false;
    	v = root->val;
    	return isValidBST(root->right);
    }

  • 0
    A

    check the following tree out.

    Following tree is the best test case for your code which is not a valid binary search tree.

    3 is the root

    3 right child 5 & left child 2

    2 Left child 1 & right child 4


  • 0
    B

    It still works in your case. I suspect it's the bug of leetcode, because it works in cpp:
    class Solution {
    public:
    Solution() {v = LONG_MIN;}
    bool isValidBST(TreeNode *root) {
    if (root == NULL) return true;
    if (isValidBST(root->left) == false) return false;
    if (root->val <= v) return false;
    v = root->val;
    return isValidBST(root->right);
    }
    long v;
    };


Log in to reply
 

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