-
Notifications
You must be signed in to change notification settings - Fork 0
/
check_bst_or_not.cpp
60 lines (46 loc) · 1.06 KB
/
check_bst_or_not.cpp
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
#include<bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node *left, *right;
Node(int val) {
data = val;
left = NULL;
right = NULL;
}
};
bool isBST(Node* root, Node* min=NULL, Node* max=NULL) {
if(root == NULL) {
return true;
}
if(min != NULL && root->data <= min->data) {
return false;
}
if(max != NULL && root->data >= max->data) {
return false;
}
bool leftValid = isBST(root->left, min, root);
bool rightValid = isBST(root->right, root, max);
return (leftValid && rightValid);
}
int main() {
Node* root = new Node(1);
root->left = new Node(2);
root->right = new Node(3);
if(isBST(root, NULL, NULL)) {
cout<<"Valid BST"<<endl;
} else
{
cout<<"Invalid BST"<<endl;
}
Node* root2 = new Node(5);
root2->left = new Node(2);
root2->right = new Node(8);
if(isBST(root2, NULL, NULL)) {
cout<<"Valid BST"<<endl;
} else
{
cout<<"Invalid BST"<<endl;
}
return 0;
}