Leetcode 255. Verify Preorder Sequence in Binary Search Tree

来源:互联网 发布:金蝶软件数据库职位 编辑:程序博客网 时间:2024/06/05 03:45

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?






public class Solution {    public boolean verifyPreorder(int[] preorder) {        return verify(preorder,0,preorder.length - 1, Integer.MIN_VALUE, Integer.MAX_VALUE);    }        private boolean verify(int[] preorder, int start, int end, int min, int max) {        if (start > end) return true;        int root = preorder[start];        if (root > max || root < min) return false;        int rightIndex = start;        while (rightIndex <= end && preorder[rightIndex] <= root) rightIndex++;        return verify(preorder, start + 1, rightIndex -1, min, root) && verify(preorder, rightIndex, end, root, max);    }}




0 0
原创粉丝点击