#include <bits/stdc++.h>
using namespace std;
int ismirror;
vector<int> pre, post;
void getpost(int root, int tail)
{
if (root > tail)
return;
int i = root + 1, 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);
post.push_back(pre[root]);
}
int main()
{
int n;
cin >> n;
pre.resize(n);
for (int i = 0; i < n; i++)
{
cin >> pre[i];
}
getpost(0, n - 1);
if (post.size() != n)
{
ismirror = 1;
post.clear();
getpost(0, n - 1);
}
if (post.size() == n)
{
cout << "YES" << endl;
cout << post[0];
for (int i = 1; i < n; i++)
{
cout << " " << post[i];
}
}
else
cout << "NO" << endl;
}
L2-004 这是二叉搜索树吗? (25 分)
最新推荐文章于 2022-03-24 16:36:45 发布