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