# 255 Verify Preorder Sequence in Binary Search Tree

Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree.

You may assume each number in the sequence is unique.

**The Idea:** In a preorder traversal of a BST, we notice the following things. A preorder traversal follows LVR (value, left, right). We observe the following: One, all the parent elements are larger than it's left children, which exception to the root. Secondly, when the number is greater than the element, then we ascending right once, before we can move left again.

**Complexity:** O(n) time where n is the number of elements and O(h) space where h is the height of the tree.

```cpp
bool verifyPreorder(vector<int>& preorder) {
    stack<int> s;
    long prev = LONG_MIN;

    for (int num : preorder) {
        while (!s.empty() && num >= s.top()) {
            prev = s.top();
            s.pop();
        }
        if (num <= prev) return false;
        s.push(num);
    }

    return true;
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://maksimdan.gitbook.io/interview-practice-problems/leetcode_sessions/255-verify-preorder-sequence-in-binary-search-tree.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
