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