Easy to understand 5 line recursive solution. not relying on INT_MIN and INT_MAX


  • 1
    C

    check whether each node is in the range

    added too variables to indicate whether the upper bound and the lower bound are valid

     bool isValidBST(TreeNode *root, int lower=0, int upper=0, bool validLower=false, bool validUpper=false)
        {
            if (root == NULL)  
                return true;
            if (validLower && root->val<=lower || validUpper && root->val >= upper)  
                return false;
            return isValidBST(root->left,lower,root->val,validLower,true) && isValidBST(root->right,root->val,upper,true,validUpper);
        }

Log in to reply
 

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