ronith
10/22/2018 - 9:58 AM

Check if a given array can represent Preorder Traversal of BST

//https://www.geeksforgeeks.org/check-if-a-given-array-can-represent-preorder-traversal-of-binary-search-tree/
#include <bits/stdc++.h>
using namespace std;

bool func (int a[], int n) {
    stack<int> s;

    int root= INT_MIN;
    for (int i=0;i<n;i++) {
        if (a[i]<root)
            return 0;
        while (!s.empty() && s.top()<a[i]) {
            root= a[i];
            s.pop();
        }
        s.push(a[i]);
    }
    return 1;
}

int main() {
    int n;
    cin>>n;
    int a[n];
    for (int i=0;i<n;i++)
        cin>>a[i];

    if (func(a,n))
        cout<< "true";
    else
        cout<< "False";
}