面试题33. 二叉搜索树的后序遍历序列

public class Main { 
   static boolean judge(int[] arr, int start, int end){

        if (start >= end) return true;
        int i = end;
        int root = arr[end];
      //i的位置是第一个大于root的数字位置,以此将数组分成两个部分 while (i > 0 && arr[i-1] > root){ --i; } for (int j=0;j<i;++j){ if (arr[j] > root){ return false; } } return judge(arr, start, i-1) && judge(arr, i, end-1); } public static boolean verifyPostorder(int[] postorder) { if (postorder == null || postorder.length == 0) return true; return judge(postorder,0,postorder.length-1); } public static void main(String[] args) { int[] numbers = {1,6,3,2,5}; boolean result = verifyPostorder(numbers); System.out.println(result); } }

  

 

示例 1:

输入: [1,6,3,2,5]
输出: false
示例 2:

输入: [1,3,2,6,5]
输出: true
 

提示:

数组长度 <= 1000 

posted @ 2020-04-08 21:41  贱人郭  阅读(122)  评论(0编辑  收藏  举报