码迷,mamicode.com
首页 > 其他好文 > 详细

255. Verify Preorder Sequence in Binary Search Tree

时间:2016-08-12 06:39:43      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

昨天写的,几乎要超时。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     }

 

255. Verify Preorder Sequence in Binary Search Tree

标签:

原文地址:http://www.cnblogs.com/warmland/p/5763403.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!