二叉搜索树的后序遍历序列
题目描述
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同
解题思路:
最后一个数一定是根节点,从根节点向前找第一个比根节点小的数,分为两个数组。第一个数组里面如果有比根节点还大的数,那就返回false。如果没有,则分拆为两个数组,递归调用下去。
public static void main(String[] args) {
Solution solution = new Solution();
int[] sequence = {1, 2, 3, 4, 5};
boolean b = solution.VerifySquenceOfBST(sequence);
System.out.println(b);
}
public boolean VerifySquenceOfBST(int[] sequence) {
if (sequence.length == 0) {
return false;
}
int length = sequence.length;
return check(sequence, 0, length - 1);
}
public boolean check(int[] sequence, int start, int end) {
if (start >= (end - 1)) {
return true;
}
int smallIdex = -1;
int bigIdex = -1;
int rootValue = sequence[end];
for (int i = end - 1; i >= start; i--) {
int value = sequence[i];
if (bigIdex == -1) {
if (value > rootValue) {
bigIdex = i;
}
continue;
} else {
}
if (smallIdex == -1) {
if (value < rootValue) {
smallIdex = i;
}
} else {
if (value > rootValue) {
return false;
}
}
}
boolean check = true;
if (bigIdex > 0) {
check = check(sequence, smallIdex + 1, bigIdex);
}
if (smallIdex > 0) {
check = check && check(sequence, start, smallIdex);
}
return check;
}