输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。
如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
思路:
已知条件:后序序列最后一个值为root;二叉搜索树左子树值都比root小,右子树值都比root大。
1、确定root;
2、遍历序列(除去root结点),找到第一个大于root的位置,则该位置左边为左子树,右边为右子树;
3、遍历右子树,若发现有小于root的值,则直接返回false;
4、分别判断左子树和右子树是否仍是二叉搜索树(即递归步骤1、2、3)。
。package April_2018; /** * @Author: Allen * @Version:v1.00 * @CreateData:2018年4月9日 上午10:53:43 */ public class HouXuBianLiShuZu { public static void main(String[] args) { Solution16 solution16 = new Solution16(); int[] intAr = {5,7,6,9,11,10,8}; System.out.println(solution16.VerifySquenceOfBST(intAr)); } } class Solution16 { public boolean VerifySquenceOfBST(int [] sequence) { if(sequence==null || sequence.length==0){ return false; } return VerifyBST(sequence,0,sequence.length-1); } public boolean VerifyBST(int [] sequence,int start,int end) { if(start>=end) return true; int rootNum=sequence[end]; int i=start; while(sequence[i]<rootNum){ i++; } int j=i; for(;j<end;j++){ if(sequence[j]<rootNum) return false; } return VerifyBST(sequence,start,i-1) && VerifyBST(sequence,i,j-1); } }