首页 > 其他 > 详细

[LeetCode]Verify Preorder Sequence in Binary Search Tree

时间:2015-11-29 14:51:37      阅读:216      评论:0      收藏:0      [点我收藏+]

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

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);
        }
    }
}

 

[LeetCode]Verify Preorder Sequence in Binary Search Tree

原文:http://www.cnblogs.com/vision-love-programming/p/5004753.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!