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.

Follow up: Could you do it using only constant space complexity?

Thoughts

  1. keep track of prev val in order to compare whether there is a new right branch

  2. keep track of lower bound value of parent node for branching to the right

Code: space complexity of O(n)

class Solution {
public:
    bool verifyPreorder(vector<int>& preorder) {
        int low = INT_MIN;
        stack<int> nodes;

        for(auto p : preorder){
            if(p < low) return false;
            while(!nodes.empty() && p > nodes.top()){
                // find the new lower bound 
                low = nodes.top(); nodes.pop();
            }

            // new reference
            nodes.push(p);
        }
        return true;
    }
};

Code: space complexity of O(n) Python

Code: Use two stack (Java)

Code: space complexity of O(1): MUST USE POINTER!

Special Thanks stefanpochmann for the reference

Last updated

Was this helpful?