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