


Consider the array ARR = [ 7, 4, 8 ] having 3 elements.
This array represents the pre-order traversal of the below tree.

Hence, the above array 'ARR' is a valid Preorder Traversal of a Binary Search Tree.
The first line of the input contains an integer, 'T,’ denoting the number of test cases.
The first line of each test case contains an integer 'N', denoting the number of elements in the array 'ARR'.
The second line of each test case contains 'N' space-separated integers denoting the array elements.
For each test case, print 1 if the array represents a valid preorder traversal of a Binary Search Tree. Otherwise, print 0.
Print the output of each test case in a new line.
You do not need to print anything. It has already been taken care of. Just implement the given function.
1 <= T <= 10
1 <= N <= 10^5
0 <= ARR[i] <= 10^9
Time Limit: 1 sec
The idea is to find the first node in the array having a value greater than the array's first element, i.e., its root. Let ARR[i] be that element. Then we will treat the elements to the right of ARR[i], including ARR[i] itself as the right subtree and all the elements before ARR[i] as the left subtree.
Now we will recursively check whether the right subtree and left subtree represent a valid Preorder traversal of a Binary Search Tree independently. We will also maintain two variables, upperBound and lowerBound, to denote the maximum possible and minimum possible that a node can contain. We will initialize the lowerBound as INT_MIN and upperBound as INT_MAX. Whenever we visit a left subtree, we will update the upperBound to the data contained on the root of the tree, and lowerBound will remain unchanged, and whenever we visit a right subtree we will update the lowerBound to the data contained on the root of the tree and upperBound will remain unchanged.
Algorithm
Instead of traversing the complete array again and again in the previous approach to find the value of firstGreaterIndex, we can use a stack to store the array elements. For the element at position i, the element at the position firstGreaterIndex will be the next Greater Element for the element ARR[i]. Hence we can use an approach similar to the algorithm to find the next Greater Element to solve our problem.
Algorithm