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