1. 程式人生 > >255. Verify Preorder Sequence in Binary Search Tree - Medium

255. Verify Preorder Sequence in Binary Search Tree - Medium

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