首页 > 其他 > 详细

255. Verify Preorder Sequence in Binary Search Tree

时间:2016-08-12 06:39:15      阅读:161      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!