码迷,mamicode.com
首页 > 其他好文 > 详细

255. Verify Preorder Sequence in Binary Search Tree

时间:2015-12-03 07:13:59      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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

255. Verify Preorder Sequence in Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/yrbbest/p/5014943.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!