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.

Consider the following binary search tree: 

     5
    / 
   2   6
  / 
 1   3

Example 1:

Input: [5,2,6,1,3]
Output: false

Example 2:

Input: [5,2,1,3,6]
Output: true

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

M1: 用stack

变量root初始时设为Integer.MIN_VALUE

对于preorder中的每个元素pre[i]: 如果小于root,直接返回false -> 当stack非空,并且pre当前元素大于栈顶元素时,弹出栈顶元素,并把最后一个弹出的元素赋值给root -> pre当前元素入栈

time: O(n), space: O(n)

class Solution {
    public boolean verifyPreorder(int[] preorder) {
        if(preorder == null || preorder.length == 0) {
            return true;
        }
        LinkedList<Integer> s = new LinkedList<>();
        int root = Integer.MIN_VALUE;
        for(int i = 0; i < preorder.length; i++) {
            if(preorder[i] < root) {
                return false;
            }
            while(!s.isEmpty() && preorder[i] > s.peekFirst()) {
                root = s.pollFirst();
            }
            s.offerFirst(preorder[i]);
        }
        return true;
    }
}

M2: constant space complexity

原文地址:https://www.cnblogs.com/fatttcat/p/10253378.html