Simple C++ solution O(n) using stack

int Solution::solve(vector<int> &pre) {
stack<int> s;
int root = INT_MIN;

for(int i =0;i<pre.size();i++){
    if(root > pre[i]){
        return 0;
    while(!s.empty() &&<pre[i]){
       root =;
return 1;



Can you explain the logic behind it


Hi Jayesh can you please explain the logic behind this code.


In pre-order traversal we can visualize that if we encounter greater number than
root node (or current node) then all number after that encountered greater number
should be greater than root node(or current node),if it happens then return (1)
otherwise return (0)


i think if we find the next largest element we start i to n-1 up to 0 . if this is wrong please tell me why?


This solution gives output 1 for {7, 10, 7}. Isn’t it wrong as this is not a valid preorder traversal of BST?