九度: http://ac.jobdu.com/problem.php?pid=1367
9. 判斷整數序列是不是二元查找樹的後序遍歷結果
題目:輸入一個整數數組,判斷該數組是不是某二元查找樹的後序遍歷的結果。如果是返回true,否則返回false。
例如輸入5、7、6、9、11、10、8,由於這一整數序列是如下樹的後序遍歷結果:
8
/ \
6 10
/ \ / \
5 7 9 11
因此返回true。
如果輸入7、4、6、5,沒有哪棵樹的後序遍歷的結果是這個序列,因此返回false。
在後續遍歷得到的序列中,最後一個元素爲樹的根結點。從頭開始掃描這個序列,比根結點小的元素都應該位於序列的左半部分;從第一個大於跟結點開始到跟結點前面的一個元素爲止,所有元素都應該大於跟結點,因爲這部分元素對應的是樹的右子樹。根據這樣的劃分,把序列劃分爲左右兩部分,我們遞歸地確認序列的左、右兩部分是不是都是二元查找樹。
#include <cstdlib>
#include <iostream>
using namespace std;
#define max 15000
bool check(int a[], int begin, int end)
{
if(begin > end)
return true;
int mid = end-1;
int root = a[end];
while(a[mid] > root && mid >= begin)
mid--;
for(int i = begin; i <= mid; i++)
if(a[i] > root)
return false;
bool left = check(a, begin, mid);
bool right = check(a, mid+1, end-1);
return left && right;
}
int main()
{
int n;
int a[max];
while(cin >> n)
{
for(int i = 0; i < n; i++)
cin >> a[i];
if(check(a, 0, n-1))
cout << "Yes" << endl;
else
cout << "No" << endl;
}
// system("pause");
return 0;
}