Skip to content

Commit 9fa4eee

Browse files
committed
Validate_BST.cpp with comments
1 parent f5888ab commit 9fa4eee

File tree

1 file changed

+18
-4
lines changed

1 file changed

+18
-4
lines changed

Trees/Binary Search Trees/Validate_BST.cpp

+18-4
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,14 @@
2424

2525

2626

27+
// C++ program to check if a given tree is BST.
2728
#include <bits/stdc++.h>
2829
using namespace std;
2930

31+
32+
3033
struct 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

4246
bool 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

6172
int 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

Comments
 (0)