输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
public class Solution { public boolean VerifySquenceOfBST(int [] sequence) { if(sequence == null || sequence.length == 0){ return false; } int root = sequence[sequence.length - 1]; int i = 0; for(;i<sequence.length-1;i++){ if(sequence[i] > root){ break; } } int j = i; for (; j<sequence.length - 1;j++){ if(sequence[j] < root){ return false; } } boolean left = true; if(i>0){ int leftSeq[] = new int[i]; for (int k = 0; k < i; k++) { leftSeq[k] = sequence[k]; } left = VerifySquenceOfBST(leftSeq); } boolean right = true; if(i<sequence.length - 1){ int rightSeq[] = new int[sequence.length - 1 - i]; for (int k = 0; k < sequence.length - 1 - i; k++) { rightSeq[k] = sequence[k+i]; } right = VerifySquenceOfBST(rightSeq); } return left&&right; } }