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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM