Skip to content

Commit aaccf0c

Browse files
committed
added validate_bst.cpp
1 parent 86bbf5d commit aaccf0c

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

validate_bst.cpp

+86
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
#include <iostream>
2+
3+
using namespace std;
4+
5+
template <class T>
6+
class Node{
7+
public:
8+
Node();
9+
~Node();
10+
T data;
11+
Node<T>* left;
12+
Node<T>* right;
13+
};
14+
15+
template <class T>
16+
Node<T>::Node(){
17+
left = NULL;
18+
right = NULL;
19+
}
20+
21+
int lastItem = -1;
22+
bool validateBstLast(Node<int>* node){
23+
if(node == NULL){
24+
return true;
25+
}
26+
if(!validateBstLast(node->left)){
27+
return false;
28+
}
29+
if(lastItem == -1){
30+
lastItem = node->data;
31+
}
32+
else if(lastItem > node->data){
33+
return false;
34+
}
35+
else{
36+
lastItem = node->data;
37+
}
38+
if(!validateBstLast(node->right)){
39+
return false;
40+
}
41+
return true;
42+
}
43+
44+
bool validateBstMinMax(Node<int>* node, int mi = -1, int ma = -1){
45+
if(node == NULL){
46+
return true;
47+
}
48+
if((mi != -1 && mi > node->data) || (ma != -1 && ma < node->data) \
49+
|| (!validateBstMinMax(node->left, mi, node->data))\
50+
|| (!validateBstMinMax(node->right, node->data, ma))){
51+
return false;
52+
}
53+
return true;
54+
}
55+
56+
int main(){
57+
58+
Node<int>* root = new Node<int>();
59+
root->data = 15;
60+
Node<int>* a = new Node<int>();
61+
a->data = 8;
62+
Node<int>* b = new Node<int>();
63+
b->data = 20;
64+
Node<int>* c = new Node<int>();
65+
c->data = 5;
66+
Node<int>* d = new Node<int>();
67+
d->data = 10;
68+
Node<int>* e = new Node<int>();
69+
e->data = 16;
70+
Node<int>* f = new Node<int>();
71+
f->data = 30;
72+
Node<int>* g = new Node<int>();
73+
g->data = 7;
74+
root->left = a;
75+
root->right = b;
76+
root->right->left = e;
77+
root->right->right = f;
78+
root->left->left = c;
79+
root->left->right = d;
80+
root->left->right->left = g;
81+
82+
cout << validateBstLast(root) << endl;
83+
cout << validateBstMinMax(root) << endl;
84+
85+
return 0;
86+
}

0 commit comments

Comments
 (0)