输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
解题思路:根据BST后序的特点,最后节点为跟节点,前面都小,后面都大,然后找到分割点,在分别判断两边是否满足。
public class Solution {
public boolean VerifySquenceOfBST(int [] sequence) {
if(sequence == null || sequence.length == 0) return false;
return verify(sequence, 0, sequence.length-1);
}
public boolean verify(int[] sequence, int start, int end){
if(sequence == null || sequence.length == 0) return false;
if(start > end) return true;
int root = sequence[end];
int i = start;
for(; i < end; i++){
if(sequence[i] > root)
break;
}
int j = i;
for(;j < end; j++){
if(sequence[j] < root) return false;
}
boolean left = true;
left = verify(sequence, start, i-1);
boolean right = true;
right = verify(sequence, i, end-1);
return left && right;
}
}
public class Solution {
public boolean VerifySquenceOfBST(int [] sequence) {
if(sequence == null || sequence.length == 0) return false;
return verify(sequence, 0, sequence.length-1);
}
public boolean verify(int[] sequence, int start, int end){
if(start > end) return true;
int pivot = end;
int root = sequence[end];
for(int i = start; i < end; i++){
if(sequence[i] > root){
pivot = i;
break;
}
}
for(int i = pivot; i < end; i++){
if(sequence[i] < root) return false;
}
return verify(sequence, start, pivot-1) && verify(sequence, pivot, end-1);
}
}