Skip to content

Commit

Permalink
Create 98_Validate-BST.cpp (#356)
Browse files Browse the repository at this point in the history
  • Loading branch information
Xtha-Sunil authored Oct 24, 2024
1 parent 07d18bb commit 8ea0125
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions C++/98_Validate-BST.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
bool isValidBST(TreeNode* root, TreeNode* minNode = nullptr, TreeNode* maxNode = nullptr) {
// Base case: an empty tree is a valid BST
if (root == nullptr) return true;

// If there is a restriction on the minimum value
if (minNode != nullptr && root->val <= minNode->val) return false;
// If there is a restriction on the maximum value
if (maxNode != nullptr && root->val >= maxNode->val) return false;

// Recursively validate the left and right subtrees
return isValidBST(root->left, minNode, root) && isValidBST(root->right, root, maxNode);
}
};
/*
2
/ \
1 3
Expected : True
10
/ \
5 15
/ \
6 20
Expected : False
*/

0 comments on commit 8ea0125

Please sign in to comment.