題目描述
輸入一個整數數組,判斷該數組是不是某二叉搜索樹的後序遍歷的結果。如果是則輸出Yes,否則輸出No。假設輸入的數組的任意兩個數字都互不相同。
題目鏈接:牛客網
解題思路
public class Main {
public static void main(String[] args) {
int[] data = {4, 8, 6, 12, 16, 14, 10};
System.out.println("true: " + verifySquenceOfBST(data));
int[] data2 = {7, 4, 6, 5};
System.out.println("false: " + verifySquenceOfBST(data2));
}
public static boolean verifySquenceOfBST(int[] sequence) {
if (sequence == null || sequence.length == 0) {
return false;
}
return verify(sequence,0,sequence.length - 1);
}
public static boolean verify(int[] sequence,int first,int last) {
if (last - first <= 1) {
return true;
}
int rootVal = sequence[last];
int cutIndex = first;
while (cutIndex < last && sequence[cutIndex] <= rootVal) {
cutIndex++;
}
for (int i = cutIndex;i < last;i++) {
if (sequence[i] < rootVal) {
return false;
}
}
return verify(sequence,first,cutIndex - 1) && verify(sequence,cutIndex,last - 1);
}
}