zoukankan      html  css  js  c++  java
  • LeetCode 255. Verify Preorder Sequence in Binary Search Tree

    原题链接在这里:https://leetcode.com/problems/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?

    题解:

    Method 1 利用stack模拟preorder. stack中放的是左子树. 遇到比stack top还要大, 说明遇到了以top 为root的右子树,把左子树连 & root 都pop出来. 

    low是当前的lower bound, pop出来说明左边扫完了,不可能出现更小的了,所以更新low. 若是遇到比low还小就说明不是preorder.

    Time Complexity: O(n). Space: O(logn).

    Method 2 是在array本身上实现stack的功能.

    index is initialized as -1, and assign the top of stack as preoder[++index]. But not initialize index as 0, and assignthe top of stack as preorder[index++].

    Since every time, the top of stack is preorder[index]. If use index++, it is not the top of stack. Also there is chance of OutOfIndexException.

    Time Complexity: O(n). Space: O(1).

    AC Java:

     1 public class Solution {
     2     public boolean verifyPreorder(int[] preorder) {
     3         /*
     4         //Method 1
     5         int low = Integer.MIN_VALUE;
     6         Stack<Integer> stk = new Stack<Integer>();
     7         for(int num : preorder){
     8             if(num < low){
     9                 return false;
    10             }
    11             while(!stk.isEmpty() && stk.peek() < num){
    12                low = stk.pop();
    13             }
    14             stk.push(num);
    15         }
    16         return true;
    17         */
    18         int index = -1;
    19         int low = Integer.MIN_VALUE;
    20         for(int num : preorder){
    21             if(num < low){
    22                 return false;
    23             }
    24             while(index >= 0 && preorder[index] < num){
    25                 low = preorder[index--];
    26             }
    27             preorder[++index] = num;
    28         }
    29         return true;
    30     }
    31 }
  • 相关阅读:
    (8) MySQL主从复制架构使用方法
    (7) MySQL数据库备份详解
    (6) MySQL慢查询日志的使用
    解决通过Nginx转发的服务请求头header中含有下划线的key,其值取不到的问题
    (5) 电商场景下的常见业务SQL处理
    (4) MySQL中EXPLAIN执行计划分析
    (3) MySQL分区表使用方法
    (2) 电商数据库表设计
    (1) Mysql高性能优化规范建议
    linux每日命令(39):lsof命令
  • 原文地址:https://www.cnblogs.com/Dylan-Java-NYC/p/5327638.html
Copyright © 2011-2022 走看看