题目:输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果,如果是则返回true,否则返回false。假设输入的数组的任意两个数字都互不相同。
package Tree;
public class VerifySqueueofBSTM {
public boolean VerifySqueueofBST(int[] squeue, int length) {
if (squeue == null || length <= 0)
return false;
int root = squeue[length - 1];
int i = 0;
for (; i < length - 1; i++) {
if (squeue[i] > root)
break;
}
int j = i;
for (; j < length - 1; j++) {
if (squeue[j] < root)
return false;
}
boolean left = true;
if (i > 0) {
left = VerifySqueueofBST(squeue, i);
}
boolean right = true;
if (i < length - 1) {
right = VerifySqueueofBST(squeue, length - i - 1);
}
return left && right;
}
public static void main(String[] args) {
VerifySqueueofBSTM verifySqueueofBSTM = new VerifySqueueofBSTM();
int[] a = { 5, 7, 6, 9, 11, 10, 8 };
int[] a2 = { 7, 4, 6, 5 };
System.out.println(verifySqueueofBSTM.VerifySqueueofBST(a, 7));
System.out.println(verifySqueueofBSTM.VerifySqueueofBST(a2, 4));
}
}
结果是
true
false
本题的思路和“重建二叉树”的思路一样,都是用递归,先判断根节点,然后是递归左孩子和右孩子。