利用前序遍历。后序数组唯一确定的就是最后一个元素必是二叉搜索树的根节点。
public class Solution {
public boolean VerifySquenceOfBST(int [] sequence) {
if(sequence == null || sequence.length == 0) return false;
return helpVerify(sequence, 0, sequence.length - 1);
}
public boolean helpVerify(int[] sequence, int start, int root){
if(start >= root) return true;
int key = sequence[root];
int i;
//找到左右子树的分界点
for(i = start; i < root; i++){
if(sequence[i] > key)
break;
}
//在右子树中判断是否有小于root的值,如果有返回false
for(int j = i; j < root; j++){
if(sequence[j] < key)
return false;
}
//再往下递归左子树和右子树
return helpVerify(sequence, start, i-1) && helpVerify(sequence, i, root-1);
}
}递归的时间复杂度为 每层的时间复杂度 * 递归的层数
每层有两个for循环,O(n)
递归层数为O(logn)
总的为 O(nlogn)

京公网安备 11010502036488号