class BSTinfo{
public:
bool isValid;
int maxVal;
int minVal;
BSTinfo(bool is, int minV, int maxV) : isValid(is), maxVal(maxV), minVal(minV){};
};
BSTinfo isValidBSTinfo(TreeNode* root){
if (root == nullptr)
return BSTinfo(true, -1, -1);
if (root->left == nullptr && root->right == nullptr)
return BSTinfo(true, root->val, root->val);
if (root->left == nullptr){
BSTinfo rInfo = isValidBSTinfo(root->right);
if (rInfo.isValid && root->val < rInfo.minVal)
return BSTinfo(true, root->val, rInfo.maxVal);
return BSTinfo(false, -1, -1);
}
if (root->right == nullptr){
BSTinfo lInfo = isValidBSTinfo(root->left);
if (lInfo.isValid && lInfo.maxVal < root->val)
return BSTinfo(true, lInfo.minVal, root->val);
return BSTinfo(false, -1, -1);
}
BSTinfo lInfo = isValidBSTinfo(root->left);
BSTinfo rInfo = isValidBSTinfo(root->right);
if (lInfo.isValid && rInfo.isValid){
if (lInfo.maxVal < root->val && root->val < rInfo.minVal)
return BSTinfo(true, lInfo.minVal, rInfo.maxVal);
}
return BSTinfo(false, -1, -1);
}
bool isValidBST(TreeNode* root) {
return isValidBSTinfo(root).isValid;
}