原来深搜还可以这样子用。
if (tl < tr) return;是关键,没有这一句则不能判断是不是二叉搜索树。
主函数中,因为不是二叉搜索树,所以建立的树大小会不足n,再试试做镜像的,如果还不行那就输出NO了。
边界的判断用while循环看起来会清爽很多,用for循环则麻烦。
题目传送
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int maxn = 1005;
int a[maxn];
int flag;
vector <int> p;
int cnt = 0;
void dfs (int left, int right)
{
if (left > right) return;
int tl = left + 1, tr = right;
if (flag == 0) {
while (tl <= right && a[tl] < a[left]) tl++;
while (tr > left && a[tr] >= a[left]) tr--;
}
else {
while (tl <= right && a[tl] >= a[left]) tl++;
while (tr > left && a[tr] < a[left]) tr--;
}
if (tl < tr) return;
dfs(left + 1, tr);
dfs(tl, right);
p.push_back(a[left]);
}
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; i++) cin >> a[i];
dfs(1, n);
if (p.size() < n) {
flag = 1;
p.clear();
dfs(1, n);
}
if (p.size() < n) {
cout << "NO" << endl;
return 0;
}
else cout << "YES" << endl;
for (int i = 0; i < p.size(); i++) {
cout << p[i];
if (i != n - 1) cout << " ";
}
return 0;
}
//记得要return 0;