C++ 13ms recursive solution


  • 0
    W
    class Solution {
        bool helper(TreeNode *root, int low, int high) {
            if(root->val < low || root->val > high)
                return false;
            if(root->left != NULL) {
                if(root->val == INT_MIN)
                    return false;
                if(helper(root->left, low, root->val-1) == false)
                    return false;
            }
            if(root->right != NULL) {
                if(root->val == INT_MAX)
                    return false;
                if(helper(root->right, root->val+1, high) == false)
                    return false;
            }
            return true;
        }
    public:
        bool isValidBST(TreeNode* root) {
            if(root == NULL) 
                return true;
            return helper(root, INT_MIN, INT_MAX);
        }
    };
    

Log in to reply
 

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