利用递归的思想,后序遍历,数组最后一个为根节点,前面小于根节点的前一部分为左子树,后一部分为右子树。左子树的所有值都要小于根节点,右子树都要大于根节点。
public class Solution {
public boolean VerifySquenceOfBST(int [] sequence) {
return splitTree(sequence,0,sequence.length-1);
}
public boolean splitTree(int[] s,int start,int end){
if(s==null||end<start)
return false;
int root=s[end];
int i=start;
while(i<end-1&&s[i]<root){
i++;
}
int j=i;
for(;j<end-1;j++){
if(s[j]<root)
return false;
}
boolean b=true;
if(i>start)
b=splitTree(s,start,i-1);
if(j<end-1)
b=splitTree(s,j,end-1);
return b;
}
}