zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    pageX,clientX,screenX,offsetX的区别
    不同的浏览器内核了解学习
    小游戏模仿
    浏览器兼容性
    hack是什么
    DOM对象
    Browser对象
    html状态码与缓存学习
    javascript对象(2)
    javascript对象(1)
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10253378.html
Copyright © 2011-2022 走看看