Verify Preorder Sequence in Binary Search Tree

medium tree stack bst

Problem

Given an array of unique integers preorder, return true if it could be the preorder traversal of a binary search tree.

Inputpreorder = [5,2,1,3,6]
Outputtrue
Valid BST: root 5, left subtree {2,1,3}, right subtree {6}.

def verify_preorder(pre):
    stack = []
    lo = float("-inf")
    for v in pre:
        if v < lo:
            return False
        while stack and stack[-1] < v:
            lo = stack.pop()
        stack.append(v)
    return True
function verifyPreorder(pre) {
  const stack = [];
  let lo = -Infinity;
  for (const v of pre) {
    if (v < lo) return false;
    while (stack.length && stack[stack.length-1] < v) lo = stack.pop();
    stack.push(v);
  }
  return true;
}
class Solution {
    public boolean verifyPreorder(int[] pre) {
        Deque stack = new ArrayDeque<>();
        int lo = Integer.MIN_VALUE;
        for (int v : pre) {
            if (v < lo) return false;
            while (!stack.isEmpty() && stack.peek() < v) lo = stack.pop();
            stack.push(v);
        }
        return true;
    }
}
bool verifyPreorder(vector& pre) {
    stack st;
    int lo = INT_MIN;
    for (int v : pre) {
        if (v < lo) return false;
        while (!st.empty() && st.top() < v) { lo = st.top(); st.pop(); }
        st.push(v);
    }
    return true;
}
Time: O(n) Space: O(n)