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.

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;
}

Last updated