The first thing we can consider here is that for a pre-order traversal array, if at any point on the right side of the array we find a larger element than the current element, and if any element after that is a smaller element, we must consider that BST is impossible from that circumvention of the order.
for example: arr [] = {40,30,35,20,80,100} it is impossible to build a valid BST.
Explanation:
Here, when we start building a tree, 40 becomes the root of BST. Now, when we go 30, it goes in the left subtree, and now we find the next larger value 30, which is 35, as we know, for any lower or smaller element located in the left subtree 30, there should be from 30 to the next larger one, i.e. 35 Here. Thus, as we move forward, we find 20 that cannot fit to the left of 30, like after the next larger element, and, of course, not like child 35, since it will violate the BST property (i.e., any element of the right element subtree should be of great value always compared to the root). Therefore, a valid BST cannot be performed.
Now, to solve this problem, we can use the stack when we use it to find the next larger element in the Code array for the next larger element . Here we just need to make sure that there will not be less after the next larger element than after.
In the code, we initially accept root as the minimum possible value of INT_MIN. If the root is less than the current element at any time, we return false. Although the current item is larger than the item at the top of the stack, we expose it and set the root as a pop-up item. And we push the current item onto the stack for further comparison.
bool check(int *arr, int n) { stack<int> s; int root=INT_MIN; for(int i=0;i<n;++i) { if(arr[i]<root) return false; while(!s.empty() && arr[i]>s.top()) { root=s.top(); s.pop(); } s.push(arr[i]); } return true; }