problem 98
This commit is contained in:
parent
39b4c5191e
commit
92b6e2833e
44
ValidateBinarySearchTree.cpp
Normal file
44
ValidateBinarySearchTree.cpp
Normal 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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
Loading…
x
Reference in New Issue
Block a user