一. 題目
輸入一個整數數組,判斷該數組是不是某二叉搜索樹的後序遍歷的結果.如果是則返回true,否則返回false.假設輸入的數組的任意兩個數字都互不相同.
代碼請到我的代碼庫中下載 Point2Offer
二. 代碼
package week_5;
/**難度係數:***
* 劍指offer: 二叉搜索樹的後序遍歷序列
* 方法: 熟悉二叉搜索樹的概念,左子樹所有結點小於根節點,右子樹所有結點都大於根節點,左右子樹仍是二叉搜索樹,鍵值都不相等
* 測試用例:
* @author dingding
* Date:2017-7-11 21:40
* Declaration: All Rights Reserved!
*/
public class No24 {
public static void main(String[] args) {
test1();
test2();
test3();
}
//solution
public static boolean verifyArrayIsBST(int[] sequence) {
// 輸入的數組不能爲空,並且有數據
if (sequence == null || sequence.length <= 0) {
return false;
}
// 有數據,就調用輔助方法
return verifyArrayIsBST(sequence, 0, sequence.length - 1);
}
private static boolean verifyArrayIsBST(int[] sequence,int start,int end){
if (start >= end) {
return true;
}
// 從左向右找第一個不大於根結點(sequence[end])的元素的位置
int index = start;
while (index < end - 1 && sequence[index] < sequence[end]) {
index++;
}
//搜索右子樹的結點大於根節點
int right = index;
while (right < end - 1 && sequence[right] > sequence[end]) {
right++;
}
if (right != end - 1) {
return false;
}
//遞歸,判斷左右子樹是不是BST
return verifyArrayIsBST(sequence, start, index - 1) && verifyArrayIsBST(sequence, index, end - 1);
}
/*=======================測試用例===============*/
private static void test1() {
int[] sequence = {5,7,6,9,11,10,8};
boolean result = verifyArrayIsBST(sequence);
if (result) {
System.out.println("YES!");
}else {
System.out.println("NO!");
}
}
private static void test2() {
int[] sequence = {7,4,6,5};
boolean result = verifyArrayIsBST(sequence);
if (result) {
System.out.println("YES!");
}else {
System.out.println("NO!");
}
}
private static void test3() {
int[] data2 = {4, 6, 7, 5};
System.out.println("true: " + verifyArrayIsBST(data2));
}
}
有不妥當之處,麻煩告知:D