-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0098-validate-binary-search-tree.cpp
More file actions
72 lines (68 loc) · 1.84 KB
/
0098-validate-binary-search-tree.cpp
File metadata and controls
72 lines (68 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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) {}
};
long long int MIN = -2147483649;
long long int MAX = -MIN-1;
class Solution
{
public:
bool validateSubTree(TreeNode *root, long long int ll, long long int ul)
{
if (root == nullptr)
return true;
if (
root->left != nullptr && (
(root->left)->val >= root->val ||
(root->left)->val <= ll ||
(root->left)->val >= ul ||
!validateSubTree(root->left, ll, root->val)
)
)
return false;
if (
root->right != nullptr && (
(root->right)->val <= root->val ||
(root->right)->val <= ll ||
(root->right)->val >= ul ||
!validateSubTree(root->right, root->val, ul)
)
)
return false;
return true;
}
bool isValidBST(TreeNode *root)
{
if (root == nullptr)
return true;
if (
root->left != nullptr && (
(root->left)->val >= root->val ||
!validateSubTree(root->left, MIN, root->val)
)
)
return false;
if (
root->right != nullptr && (
(root->right)->val <= root->val ||
!validateSubTree(root->right, root->val, MAX)
)
)
return false;
return true;
}
};
int main() {
TreeNode rl(3);
TreeNode rr(78);
TreeNode r(49, nullptr, &rr);
TreeNode l(1);
TreeNode root(-59, nullptr, &r);
Solution s;
s.isValidBST(&root);
}