/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ classSolution { public: boolisValidBST(TreeNode* root){ bool res = true; helper(root, res); return res; }
pair<int, int> helper(TreeNode *root, bool &res) { if (!root) return {INT_MAX, INT_MIN}; int max = root->val, min = root->val; if (root->left) { auto l = helper(root->left, res); min = std::min(min, l.first); max = std::max(max, l.second); res &= (l.second < root->val); } if (root->right) { auto r = helper(root->right, res); min = std::min(min, r.first); max = std::max(max, r.second); res &= (root->val < r.first); } return {min, max}; } };