24
24
25
25
26
26
27
+ // C++ program to check if a given tree is BST.
27
28
#include < bits/stdc++.h>
28
29
using namespace std ;
29
30
31
+
32
+
30
33
struct Node {
34
+ // structure of a node of the tree.
31
35
int data;
32
36
struct Node *left, *right;
33
37
@@ -41,31 +45,41 @@ struct Node {
41
45
42
46
bool validate (Node* root,long long int min , long long int max){
43
47
if (!root)
44
- return true ;
45
- bool ans = false ;
48
+ return true ; // if the root is null then it is a valid BST. it means that the tree is empty or we had reached the end of tree.
49
+ // initializing the ans variable to false (temporarily).
50
+ bool ans = false ;
51
+
52
+ // checking if the root's data is in the range of min and max.
46
53
if (root->data <max && root->data >min)
47
54
ans = true ;
48
55
else
49
- return ans;
50
- return ans && validate (root->left ,min,root->data ) &&
56
+ return ans; // if the root's data is not in the range of min and max then it is not a valid BST. hence returning false.
57
+
58
+ // changing min and max for the left and right subtree. and checking for the left and right subtree with respesct to tree root and returning the ans.
59
+ return ans && validate (root->left ,min,root->data ) &&
51
60
validate (root->right ,root->data ,max);
52
61
}
53
62
54
63
55
64
bool isValidBST (Node* root) {
56
65
if (!root)
57
66
return true ;
67
+
68
+ // calling validate function so that it can check for the left and right subtree .. while giving the range of the values of the nodes.
58
69
return validate (root ,-9223372036854775807 ,9223372036854775807 );
59
70
}
60
71
61
72
int main ()
62
73
{
74
+
75
+ // Initializing the tree.
63
76
struct Node * root = new Node (3 );
64
77
root->left = new Node (2 );
65
78
root->right = new Node (5 );
66
79
root->left ->left = new Node (1 );
67
80
root->left ->right = new Node (4 );
68
81
82
+ // calling the function to check BST.
69
83
if (isValidBST (root))
70
84
cout << " Is BST" ;
71
85
else
0 commit comments