// C++ program to check if a given array can represent
// a preorder traversal of a BST or not
#include <bits/stdc++.h>
using namespace std;
void buildBSThelper(int& preIndex, int n, vector<int> &pre,
int min, int max) {
// If we have processed all elements, return
if (preIndex >= n)
return;
// If the current element lies between min and max,
// it can be part of the BST
if (min <= pre[preIndex] && pre[preIndex] <= max) {
// Treat the current element as the root of
// this subtree
int rootData = pre[preIndex];
preIndex++;
buildBSThelper(preIndex, n, pre, min, rootData);
buildBSThelper(preIndex, n, pre, rootData, max);
}
}
bool canRepresentBST(vector<int> &arr) {
// Set the initial min and max values
int min = INT_MIN, max = INT_MAX;
// Start from the first element in
// the array
int preIndex = 0;
int n = arr.size();
buildBSThelper(preIndex, n, arr, min, max);
// If all elements are processed, it means the
// array represents a valid BST
return preIndex == n;
}
int main() {
vector<int> pre = {40, 30, 35, 80, 100};
if (canRepresentBST(pre))
cout << "true\n";
else
cout << "false\n";
return 0;
}