1043 Is It a Binary Search Tree
题目大意
将一个二叉排序树或者其镜像树的先序序列,转为后序序列
算法思想
- 先按不是镜像来做,将二叉排序树的后序求出来,如果大小不是n,则有可能镜像有可能是错二叉排序树,就可以按镜像处理一次,求出其二叉排序树后序序列,如果大小还不是n,就是错的二叉排序树
代码
#include<iostream>
#include<vector>
using namespace std;
vector<int>pre, post;
bool mir = false;
int n;
void turnpost(int x, int y) {//转后序
if (x > y)
return;
int i = x + 1;
int j = y;
if (!mir) {//不是镜像
while (i <= y && pre[i] < pre[x])
i++;
while (j > x && pre[j] >= pre[x])
j--;
}
else {//是镜像
while (i <= y && pre[i] >= pre[x])
i++;
while (j > x && pre[j] < pre[x])
j--;
}
if (j != x)//有左子树
turnpost(x + 1, j);
if (i != y + 1)//有右子树
turnpost(i, y);
post.push_back(pre[x]);
return;
}
int main() {
cin >> n;
pre.resize(n);
for (int i = 0; i < n; i++)
cin >> pre[i];
turnpost(0, n - 1);//默认不是镜像转一次
if (post.size() != n)//有可能是镜像
{
mir = true;
post.clear();
turnpost(0, n - 1);
}
if(post.size()==n)//已经转成功
{
cout << "YES" << endl << post[0];
for (int i = 1; i < post.size(); i++)
cout << " " << post[i];
}
else//一定不符合
cout << "NO";
return 0;
}