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

给一个数组,验证是否为一个二叉搜索树的先序遍历出的序列。

二叉树的特点是:左<根<右,如果用中序遍历得到的结果就是有序数组,而先序遍历的结果就不是有序数组。

Python:

# Time:  O(n)
# Space: O(h)
class Solution2:
    # @param {integer[]} preorder
    # @return {boolean}
    def verifyPreorder(self, preorder):
        low = float("-inf")
        path = []
        for p in preorder:
            if p < low:
                return False
            while path and p > path[-1]:
                low = path[-1]
                path.pop()
            path.append(p)
        return True

Python:  

# Time:  O(n)
# Space: O(1)
class Solution:
    # @param {integer[]} preorder
    # @return {boolean}
    def verifyPreorder(self, preorder):
        low, i = float("-inf"), -1
        for p in preorder:
            if p < low:
                return False
            while i >= 0 and p > preorder[i]:
                low = preorder[i]
                i -= 1
            i += 1
            preorder[i] = p
        return True

C++:

// Time:  O(n)
// Space: O(h)
class Solution2 {
public:
    bool verifyPreorder(vector<int>& preorder) {
        int low = INT_MIN;
        stack<int> path;
        for (auto& p : preorder) {
            if (p < low) {
                return false;
            }
            while (!path.empty() && p > path.top()) {
                // Traverse to its right subtree now.
                // Use the popped values as a lower bound because
                // we shouldn't come across a smaller number anymore.
                low = path.top();
                path.pop();
            }
            path.emplace(p);
        }
        return true;
    }
};

C++:

// Time:  O(n)
// Space: O(1)
class Solution {
public:
    bool verifyPreorder(vector<int>& preorder) {
        int low = INT_MIN, i = -1;
        for (auto& p : preorder) {
            if (p < low) {
                return false;
            }
            while (i >= 0 && p > preorder[i]) {
                low = preorder[i--];
            }
            preorder[++i] = p;
        }
        return true;
    }
};

  

  

类似题目:

[LeetCode] 144. Binary Tree Preorder Traversal 二叉树的先序遍历

[LeetCode] 98. Validate Binary Search Tree 验证二叉搜索树

  

 

All LeetCode Questions List 题目汇总

posted @ 2018-10-02 09:16  轻风舞动  阅读(617)  评论(0编辑  收藏  举报