题目:
一棵二叉搜索树可被递归地定义为具有下列性质的二叉树:
对于任一结点,其左子树中所有结点的键值小于该结点的键值;
其右子树中所有结点的键值大于等于该结点的键值;
其左右子树都是二叉搜索树。
所谓二叉搜索树的“镜像”,即将所有结点的左右子树对换位置后所得到的树。
给定一个整数键值序列,现请你编写程序,判断这是否是对一棵二叉搜索树或其镜像进行前序遍历的结果。
//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";
}