problem 98

This commit is contained in:
Buduf 2022-04-14 13:36:11 +02:00
parent 39b4c5191e
commit 92b6e2833e

View File

@ -0,0 +1,44 @@
#include <bits/stdc++.h>
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;
}
}
}
};