2424
2525
2626
27+ // C++ program to check if a given tree is BST.
2728#include < bits/stdc++.h>
2829using namespace std ;
2930
31+
32+
3033struct Node {
34+ // structure of a node of the tree.
3135 int data;
3236 struct Node *left, *right;
3337
@@ -41,31 +45,41 @@ struct Node {
4145
4246bool validate (Node* root,long long int min , long long int max){
4347 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.
4653 if (root->data <max && root->data >min)
4754 ans = true ;
4855 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 ) &&
5160 validate (root->right ,root->data ,max);
5261}
5362
5463
5564 bool isValidBST (Node* root) {
5665 if (!root)
5766 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.
5869 return validate (root ,-9223372036854775807 ,9223372036854775807 );
5970 }
6071
6172int main ()
6273{
74+
75+ // Initializing the tree.
6376 struct Node * root = new Node (3 );
6477 root->left = new Node (2 );
6578 root->right = new Node (5 );
6679 root->left ->left = new Node (1 );
6780 root->left ->right = new Node (4 );
6881
82+ // calling the function to check BST.
6983 if (isValidBST (root))
7084 cout << " Is BST" ;
7185 else
0 commit comments