題目:
一棵二叉搜尋樹可被遞歸地定義為具有下列性質的二叉樹:
對于任一結點,其左子樹中所有結點的鍵值小于該結點的鍵值;
其右子樹中所有結點的鍵值大于等于該結點的鍵值;
其左右子樹都是二叉搜尋樹。
所謂二叉搜尋樹的“鏡像”,即将所有結點的左右子樹對換位置後所得到的樹。
給定一個整數鍵值序列,現請你編寫程式,判斷這是否是對一棵二叉搜尋樹或其鏡像進行前序周遊的結果。
//L2 - 004
#include <iostream>
#include <vector>
using namespace std;
const int N = 1005;
int n, isMirror = 0;
int pre[N];
vector<int> p;
void getPost(int root,int tail)
{
if(root > tail) return;
int i = root+1;
int j = tail;
if(!isMirror)
{
while(i <= tail && pre[root] > pre[i]) i ++ ;
while(j > root && pre[root] <= pre[j]) j -- ;
}
else
{
while(i <= tail && pre[root] <= pre[i]) i ++ ;
while(j > root && pre[root] > pre[j]) j -- ;
}
if(i - j != 1) return; //如果分界點對不上的話說明不是二叉搜尋樹
getPost(root + 1, j);
getPost(i, tail);
p.push_back(pre[root]);
}
int main(){
cin >> n;
for(int i = 0; i < n; i ++ ) cin >> pre[i];
getPost(0,n-1);
if(p.size() != n)
{
isMirror = 1;
getPost(0, n-1); //如果size對不上,那麼認為有是鏡像的可能,再來一次鏡像的測試
}
//跑兩次後還是不行的話,那麼就不是二叉搜尋樹
if(p.size() == n)
{
cout << "YES" << endl;
for(int i = 0; i < n; i ++ )
{
cout << p[i];
if(i != n-1) cout << " ";
}
}else cout<<"NO";
}