输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
思路
(1)本道题整体上和面试题7:重建二叉树思路较为一致。首先找到根结点,每次用根结点来进行分割左右子树,抓住左右子树和二叉搜索树中序遍历的特性。左边<根<右边!
(2)在提交中有两个错误点。 1) 递归终止条件。2)关于有子树为空的情况。具体还有点没理清。
解法
nowcoder的AC
提交时间:2020-01-10 ,语言:Java ,运行时间: 19 ms ,占用内存:9416K ,状态:答案正确
public class Solution {
public boolean VerifySquenceOfBST(int [] sequence) {
if(sequence.length < 1){
return false;
}
return VerifySquenceOfBST(sequence, 0, sequence.length-1);
}
boolean VerifySquenceOfBST(int [] sequence, int start, int end){
//if(start == end){ error1
if(start >= end){
return true;
}
// normal situation
int root = sequence[end];
int index = start;
while(sequence[index] < root && index < end ){
index ++;
// if(index >end-1 ){ error2
// return false;
// }
}
for(int i = index; i<end; i++){
if(sequence[i] < root){
return false;
}
}
return VerifySquenceOfBST(sequence, start, index-1) && VerifySquenceOfBST(sequence, index, end-1);
}
}