• 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.

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

    链接: http://leetcode.com/problems/verify-preorder-sequence-in-binary-search-tree/

    题解:

    使用Stack来模拟preorder traversal ->   mid, left, right。主要代码都是参考了Stefan Pochmann的解答。

    Time Complexity - O(n), Space Complexity - O(logn)

    public class Solution {
        public boolean verifyPreorder(int[] preorder) {
            int low = Integer.MIN_VALUE;
            Stack<Integer> stack = new Stack<>();
            for(int i : preorder) {
                if(i < low)
                    return false;
                while(!stack.isEmpty() && i > stack.peek())
                    low = stack.pop();
                stack.push(i);
            }
            
            return true;
        }
    }

    不使用Stack,Space Complexity O(1)的解法, 利用了原数组

    public class Solution {
        public boolean verifyPreorder(int[] preorder) {
            int low = Integer.MIN_VALUE, index = -1;
            for(int i : preorder) {
                if(i < low)
                    return false;
                while(index >= 0 && i > preorder[index])
                    low = preorder[index--];
                preorder[++index] = i;
            }
            
            return true;
        }
    }

    Reference:

    https://leetcode.com/discuss/51543/java-o-n-and-o-1-extra-space

    https://leetcode.com/discuss/52060/72ms-c-solution-using-one-stack-o-n-time-and-space

    https://leetcode.com/discuss/65241/ac-python-o-n-time-o-1-extra-space

    https://leetcode.com/discuss/68862/my-c-solution-easy-to-understand

  • 相关阅读:
    数据库基础(2)
    数据库基础
    多线程(3)
    多线程(2)
    多线程(1)
    并发编程(3)
    软件工程——个人总结
    软件工程第二次作业-结对编程
    软件工程第二次作业——结对编程心得体会
    软件工程第一次作业补充
  • 原文地址:https://www.cnblogs.com/yrbbest/p/5014943.html
Copyright © 2020-2023  润新知