题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
利用二叉搜索树(二叉排序树)的性质,左小于根小于右。
且后序遍历中,根是数组的最后一个元素,则把根取出来,将数组其余分为左、右两部分,只要左子树全部小于根,且右子树全部大于根,则满足条件,继而对左、右子树再分别调用判断函数。
解法:
public class Solution {
public boolean VerifySquenceOfBST(int [] sequence) {
if(sequence.length == 0) {
return false;
}
if(sequence.length == 1) {
return true;
}
return judge(sequence, 0, sequence.length - 1);
}
public boolean judge(int[] a, int start, int end) {
if(start >= end) {
return true;
}
int i = start;
while(a[i] < a[end]) {
i++;
}
for(int j = i; j < end; j++) {
if(a[j] < a[end]) {
return false;
}
}
return judge(a, start, i - 1) && judge(a, i, end - 1);
}
}