[LeetCode]Verify Preorder Sequence in Binary Search Tree

第一个是递归的方法,但是空间复杂度不是线性的

public class Solution {
    public boolean verifyPreorder(int[] preorder) {
        return helper(preorder, 0, preorder.length - 1);
    }
    public boolean helper(int[] nums, int left, int right) {
        if (left > right || left < 0 || right >= nums.length) {
            return true;
        }
        if (left == right) {
            return true;
        }
        int i = left;
        boolean flg = false;
        for (; i <= right; i++) {
            if (nums[i] > nums[left]) {
                flg = true;
                break;
            }
        }
        for (int j = i; j <= right; j++) {
            if (nums[j] <= nums[left]) {
                return false;
            }
        }
        if (flg) {
            return helper(nums, left + 1, i - 1) && helper(nums, i, right);
        } else {
            return helper(nums, left + 1, right);
        }
    }
}

 

posted @ 2015-11-29 14:35  Weizheng_Love_Coding  阅读(136)  评论(0编辑  收藏  举报