https://www.geeksforgeeks.org/batch/gfg-160-problems/track/tree-gfg-160/problem/check-for-bst
Solution 1 Naive approch
class Solution {
public:
// Function to check whether a Binary Tree is BST or not.
bool isBST(Node* root) {
// Your code here
vector<int> res ;
return helper(root , res);
}
private:
bool helper(Node* root, vector<int >& res){
inorder(root , res);
for(int i =1; i <res.size() ; i++){
if(res[i] <= res[i-1]){
return false;
}
}
return true;
}
void inorder(Node* root, vector<int >& res){
if(!root) return;
inorder(root->left , res);
res.push_back(root->data);
inorder(root->right , res);
}
};
time O(n) Space O(n)
Optimal approch min-max
class Solution2 {
public:
bool isBST(Node* root) {
return validate(root, LONG_MIN, LONG_MAX);
}
private:
bool validate(Node* root, long minVal, long maxVal) {
if (!root) return true;
if (root->data <= minVal || root->data >= maxVal) {
return false;
}
return validate(root->left, minVal, root->data) &&
validate(root->right, root->data, maxVal);
}
};
time O(n) Space O(h)