10-line C++ recursive solution 12ms


  • 0

    Helper function isValidBSTInRange checks if a binary tree is a valid BST with node values in range [low, high].

        bool isValidBST(TreeNode* r) {
            return isValidBSTInRange(r, INT_MIN, INT_MAX);
        }
        bool isValidBSTInRange(TreeNode* r, int low, int high) {
            if (!r) return true;
            int rv = r->val;
            if (rv < low || rv > high || 
                (rv == INT_MIN && r->left) || (rv == INT_MAX && r->right)) return false;
            return isValidBSTInRange(r->left,low,rv-1) && isValidBSTInRange(r->right,rv+1,high);
        }
    

Log in to reply
 

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