#include struct TreeNode { int val; TreeNode* left; TreeNode* right; TreeNode() : val(0), left(nullptr), right(nullptr) {} TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {} }; class Solution { public: bool isValidBST(TreeNode* root) { if (root != nullptr) { return valid(root, INT_MIN, INT_MAX, false, false); } else { return true; } } bool valid(TreeNode* t, int min, int max, bool wasMin, bool wasMax) { if ((wasMin && t->val <= min) || (wasMax && t->val >= max)) { return false; } if (t->left != nullptr) { bool l = valid(t->left, min, t->val, wasMin, true); if (t->right != nullptr) { return l && valid(t->right, t->val, max, true, wasMax); } else { return l; } } else { if (t->right != nullptr) { return valid(t->right, t->val, max, true, wasMax); } else { return true; } } } };