1
+ #include < iostream>
2
+ using namespace std ;
3
+
4
+ /* *
5
+ * Definition for a binary tree node.
6
+ */
7
+ struct TreeNode {
8
+ int val;
9
+ TreeNode *left;
10
+ TreeNode *right;
11
+ TreeNode (int x) : val(x), left(NULL ), right(NULL ) {}
12
+ };
13
+
14
+ TreeNode* insertLeft (TreeNode* root, int value) {
15
+ root->left = new TreeNode (value);
16
+ return root->left ;
17
+ }
18
+
19
+ TreeNode* insertRight (TreeNode* root, int value) {
20
+ root->right = new TreeNode (value);
21
+ return root->right ;
22
+ }
23
+
24
+ class Solution {
25
+ public:
26
+ bool isValid (TreeNode* root, int minVal, int maxVal, bool noMin, bool noMax) {
27
+ if (root == NULL ) {
28
+ return true ;
29
+ }
30
+ if (!noMin && root->val <= minVal) {
31
+ return false ;
32
+ }
33
+ if (!noMax && root->val >= maxVal) {
34
+ return false ;
35
+ }
36
+ bool rightValid = false ;
37
+ bool leftValid = false ;
38
+ rightValid = isValid (root->right , root->val , maxVal, false , noMax);
39
+ leftValid = isValid (root->left , minVal, root->val , noMin, false );
40
+ return rightValid && leftValid;
41
+ }
42
+ bool isValidBST (TreeNode* root) {
43
+ return isValid (root, 0 , 0 , true , true );
44
+ }
45
+ };
46
+
47
+ int main () {
48
+ auto root1 = new TreeNode (50 );
49
+ Solution solver;
50
+ cout << solver.isValidBST (root1) << endl; // true
51
+
52
+ auto root2 = new TreeNode (50 );
53
+ insertLeft (root2, 30 );
54
+ insertLeft (root2->left , 10 );
55
+ insertRight (root2, 70 );
56
+ insertRight (root2->right , 80 );
57
+ insertRight (root2->left , 40 );
58
+ insertLeft (root2->right , 60 );
59
+ cout << solver.isValidBST (root2) << endl; // true
60
+
61
+ auto root3 = new TreeNode (50 );
62
+ insertLeft (root3, 30 );
63
+ insertLeft (root3->left , 20 );
64
+ insertRight (root3, 80 );
65
+ insertRight (root3->right , 90 );
66
+ insertRight (root3->left , 60 );
67
+ insertLeft (root3->right , 70 );
68
+ cout << solver.isValidBST (root3) << endl; // false
69
+ }
0 commit comments