[LeetCode255]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?

Hide Company Tags Zenefits
Hide Tags Tree Stack
Hide Similar Problems (M) Binary Tree Preorder Traversal

preorder: (root)left, right.
BST: LEFT<(=) ROOT

    bool verifyPreorder(vector<int>& preorder) {
        stack<int> stk;
        int low = INT_MIN;
        for(int n : preorder){
            if(n<low) return false;
            while(!stk.empty() && n > stk.top()){
                low = stk.top();
                stk.pop();
            }
            stk.push(n);
        }
        return true;
    }

follow up question 問能不能O(1) space?
O(1)的做法讓我看到了Bloomberg面試我的stable sort。。。

bool verifyPreorder(vector<int>& preorder) {
    int low = INT_MIN, i = -1;
        for(int n : preorder){
            if(n < low) return false;
            while(i>=0 && n > preorder[i]) low = preorder[i--];
            preorder[++i] = n;
        }
        return true;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章