原来深搜还可以这样子用。
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;
本文探讨了如何利用深度优先搜索(DFS)判断并构建二叉搜索树,关键在于`if(tl<tr)`条件的使用。通过调整边界判断和镜像遍历,确保树结构完整。
256

被折叠的 条评论
为什么被折叠?



