255. Verify Preorder Sequence in Binary Search Tree

昨天写的,几乎要超时。600ms+ = =换了种方法直接LTE了

 1     public boolean verifyPreorder(int[] preorder) {
 2         return helper(preorder, 0, preorder.length - 1);
 3     }
 4     
 5     private int findNextBigger(int[] preorder, int start, int end) {
 6         for(int i = start + 1; i <= end; i++) {
 7             if(preorder[i] > preorder[start]) {
 8                 return i;
 9             }
10         }
11         return end + 1;
12     }
13     
14     private boolean helper(int[] preorder, int start, int end) {
15         if(start >= end) {
16             return true;
17         }
18         int index = findNextBigger(preorder, start, end);
19         for(int i = index; i <= end; i++) {
20             if(preorder[i] < preorder[start]) {
21                 return false;
22             }
23         }
24         boolean left = helper(preorder, start + 1, index - 1);
25         boolean right = helper(preorder, index, end);
26         return left && right;
27     }

 

posted @ 2016-08-12 01:00  warmland  阅读(174)  评论(0编辑  收藏  举报