首页 > 其他 > 详细

255. Verify Preorder Sequence in Binary Search Tree

时间:2015-12-03 07:10:54      阅读:272      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!