题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
解题思路
首先找到树的根结点,然后找出比根结点小的和比根结点大的元素范围,若符合要求,则分别是根结点的左右子树,然后继续递归判断。
实现
public class Solution {
public boolean VerifySquenceOfBST(int [] sequence) {
if (sequence == null || sequence.length <= 0) return true;
return VerifySquenceOfBSTRecursion(sequence, 0 ,sequence.length - 1);
}
private boolean VerifySquenceOfBSTRecursion(int[] sequence, int start, int end) {
if (start>=end) return true;
int root = sequence[end];
int endLeft = start - 1;
boolean isInLeft = true;
for(int i = start; i < end; i++){
if (sequence[i] < root && isInLeft){
endLeft = i;
}else if (sequence[i] < root && !isInLeft) return false;
else if (sequence[i] > root) isInLeft = false;
}
return VerifySquenceOfBSTRecursion(sequence, start, endLeft) &&
VerifySquenceOfBSTRecursion(sequence, endLeft + 1, end - 1);
}
}