#include <iostream>
#include <vector>
#include <climits>
using namespace std;
bool isBSTUtil(const vector<int>& preorder, int& index, int minValue, int maxValue) {
// Base case: If index reaches the size of preorder, return true
if (index >= preorder.size()) return true;
// Get the current value and check if it is within the allowed range (BST property)
int currentVal = preorder[index];
if (currentVal < minValue || currentVal > maxValue) return false;
// Move to the next value
index++;
// Recursively check the left and right subtree
// For the left subtree, the allowed range is (minValue, currentVal)
bool leftValid = isBSTUtil(preorder, index, minValue, currentVal);
// For the right subtree, the allowed range is (currentVal, maxValue)
bool rightValid = isBSTUtil(preorder, index, currentVal, maxValue);
return leftValid && rightValid;
}
bool isBST(const vector<int>& preorder) {
int index = 0;
return isBSTUtil(preorder, index, INT_MIN, INT_MAX);
}
int main() {
vector<int> preorder = {2 , 1 , 3 , 4 , 5}; // Example pre-order traversal
if (isBST(preorder))
cout << "The given pre-order traversal is a BST" << endl;
else
cout << "The given pre-order traversal is not a BST" << endl;
return 0;
}
I2luY2x1ZGUgPGlvc3RyZWFtPgojaW5jbHVkZSA8dmVjdG9yPgojaW5jbHVkZSA8Y2xpbWl0cz4KdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCmJvb2wgaXNCU1RVdGlsKGNvbnN0IHZlY3RvcjxpbnQ+JiBwcmVvcmRlciwgaW50JiBpbmRleCwgaW50IG1pblZhbHVlLCBpbnQgbWF4VmFsdWUpIHsKICAgIC8vIEJhc2UgY2FzZTogSWYgaW5kZXggcmVhY2hlcyB0aGUgc2l6ZSBvZiBwcmVvcmRlciwgcmV0dXJuIHRydWUKICAgIGlmIChpbmRleCA+PSBwcmVvcmRlci5zaXplKCkpIHJldHVybiB0cnVlOwoKICAgIC8vIEdldCB0aGUgY3VycmVudCB2YWx1ZSBhbmQgY2hlY2sgaWYgaXQgaXMgd2l0aGluIHRoZSBhbGxvd2VkIHJhbmdlIChCU1QgcHJvcGVydHkpCiAgICBpbnQgY3VycmVudFZhbCA9IHByZW9yZGVyW2luZGV4XTsKICAgIGlmIChjdXJyZW50V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