题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
二叉树后续遍历的顺序为:左<根<右。这里结合图(懒得画了盗的,哈哈)可以看出所有子树的根节点就是该子数组的最后一位。所以我们只需要已根节点为基准点吧数组分为左子树和右子树,然后以此类推->递归。直到我们的首索引>=根索引。
public class Solution {
public boolean VerifySquenceOfBST(int [] sequence) {
if(sequence==null||sequence.length<=0)return false;
return isBST(sequence,0,sequence.length-1);
}
public boolean isBST(int [] sequence,int start,int end){
if(start>=end)return true;
int index=0;
int root = sequence[end];
for(;index<end;index++){ // 记录节点,该节点之前为左子树,该节点之后为右子树。左子树每个值都小于根节点所以做完此操作只需判断右子树是否都大于根节点就可以了。
if(sequence[index]>root)break;
}
for(int j =index;j<end;j++){
if(sequence[j]<root){
return false;
}
}
return isBST(sequence,0,index-1)&&isBST(sequence,index,end-1);
}
}
- 时间复杂度:O(nlogn)。
- 空间复杂度:O(logn)。