二叉搜索树有其规律,中序遍历是一个递增数组,因此后续遍历也有了规律,那就是左子树一定比根节点小,右子树一定比根节点大,而后续遍历最后一个结点必定是根节点。后续遍历是左->右->根的顺序遍历,所以按照规则来说,在后续遍历数组中,从第一个大于根节点的数开始,剩下的数都应该大于根结点。如果违背这个规律说明这个数组不是一个二叉搜索树的后序遍历结果,返回false。然后用递归的思想分别对左右子树做判断,当所有数都遍历过了还没有返回false的时候,就说明没有违背规律,现在返回true即可。
public class Solution {
public boolean VerifySquenceOfBST(int [] sequence) {
if(sequence.length==0)
return false; //一般题都要考虑一下特殊情况
int start=0;
int end=sequence.length-1;
return isTrue(sequence,start,end);
}
public boolean isTrue(int[] sequence,int start,int end){
if(start>=end)
return true; //遍历完事还没有失败,则说明成功
int mid=start;
while(sequence[mid]<sequence[end]){
mid++; //找第一个大于根结点的数,这个数就是左右子树的分割点。
}
for(int i=mid;i<end;i++){
if(sequence[i]<sequence[end])
return false; //如果在右子树中发现小于根节点的数,说明不是二叉搜索树
}
return isTrue(sequence,start,mid-1)&&isTrue(sequence,mid,end-1);
}
}