首先介绍二叉搜索树:
若左子树不为空,左子树所有的整数小于等于根,若右子树不为空,右子树所有的整数大于等于根。
后序遍历,左右根的遍历顺序造成,最后一个数肯定是根。
剑指offer一道算法题:输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
public class Solution {
public boolean VerifySquenceOfBST(int [] sequence) {
int count = sequence.length-1;
int start = 0;
if(count >= 0){
return digui(sequence, start, count);
}else{
return false;
}
}
public boolean digui(int []sequence, int start, int end){
boolean result = true;
int first = 0;
while(first < end){
if(sequence[first] > sequence[end]){
break;
}else{
first++;
}
}
//first之前的肯定都小于root
for(int i =first+1;i<(end-first); i++){
if(sequence[i]<sequence[end]){
return false;
}
}
//如果有左子树,开始递归
if(first > start){
result = digui(sequence, start, first-1);
}
//如果有右子树,开始递归
if(end-1 > start){
result = digui(sequence, first, end-1);
}
return result;
}
}
本人代码,通过递归方式,判断每一层是否符合要求。