问题:输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
解答:
import java.util.Arrays;
import java.util.Vector;
public class Solution {
public boolean VerifySquenceOfBST(int[] sequence) {
//基准情况,递归终止条件
if(sequence==null || sequence.length<=0)
return false;
int root = sequence[sequence.length-1];
int i=0;
for(;i<sequence.length-1;i++)
if(sequence[i]>root)
break;
int j=i;
for(;j<sequence.length-1;j++){
if(sequence[j]<root)
return false;
}
boolean left = true;
boolean right = true;
//递归演进,我们思考的过程,如何推进
if(i>0)
left = VerifySquenceOfBST(Arrays.copyOfRange(sequence,0,i));
if(j==sequence.length-2)
right = VerifySquenceOfBST(Arrays.copyOfRange(sequence,i,sequence.length-1));
//返回结果
return (left && right);
}
}