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

  • 相关阅读:
    MySQL-MMM方案
    MySQL双主复制
    MySQL主从复制
    Keepalived实现高可用
    CentOS7.2 部署Haproxy 1.7.2
    博客园写随笔时用数学公式
    Java中有三种移位运算符
    VS Code配置C/C++环境
    Visual Studio Code 如何编写运行 C、C++ 程序?
    头一次知道“原地算法”?!
  • 原文地址:https://www.cnblogs.com/fatttcat/p/10253378.html
Copyright © 2011-2022 走看看