您的位置:首页 > 理论基础 > 数据结构算法

团体程序设计天梯赛-练习集 L2-004. 这是二叉搜索树吗?GU

2016-07-05 12:00 190 查看
团体程序设计天梯赛-练习集

L2-004. 这是二叉搜索树吗?

https://www.patest.cn/contests/gplt/L2-004

根据二叉搜索树的定义进行递归,先找到左枝与右枝的分界,再递归搜索左枝与右枝。在递归的同时就可以记录后序排序结果。

注意:

如果没有右枝要单独判断。

递归最后要返回true。

后面注释掉是的是两个递归的方法。

#include<iostream>
#include<cstdio>
using namespace std;
int A[1005], cnt, B[1005];
bool thistree(int s, int d,int tab) {
if (s > d - 1) {
return true;
}
if (s == d - 1) {
B[cnt++] = A[s];
return true;
}
int i;
bool flag = true;
for (i = s + 1; i < d; i++) {
if (tab ? A[s] <= A[i] : A[s] > A[i]) {
flag = false;
if (!thistree(s + 1, i, tab)) {
return false;
}
break;
}
}
if (flag) {
if (!thistree(s + 1, d, tab)) {
return false;
}
}
else {
for (int j = i; j < d; j++) {
if (tab ? A[s] > A[j]:A[s] <= A[j]) {
return false;
}
}
if (!thistree(i, d, tab)) {
return false;
}
}
B[cnt++] = A[s];
return true;
}
int main() {
int N;
while (scanf("%d", &N) != EOF) {
if (N == 0) {
printf("YES\n");
continue;
}
for (int i = 0; i < N; i++) {
scanf("%d", &A[i]);
}
if (thistree(0, N, 1)) {
cnt = 0;
printf("YES\n");
for (int i = 0; i < N - 1; i++) {
printf("%d ", B[i]);
}
/*pr(0, N - 1, 1);*/
printf("%d\n", B[N - 1]);
}
else if (thistree(0, N, 0)) {
cnt = 0;
printf("YES\n");
for (int i = 0; i < N-1; i++) {
printf("%d ", B[i]);
}
/*pr(0, N - 1, 0);*/
printf("%d\n", B[N - 1]);
}
else {
printf("NO\n");
}
}
return 0;
}
//void pr(int l, int r, int tab) {
//  if (l > r) return; //debug 越界判断
//  if (l == r) {
//      printf(++cnt == 1 ? "%d" : " %d", A[l]);
//      return;
//  }
//  int root = A[l], i;
//  bool fl, fr;
//  for (i = l + 1; i <= r + 1; i++) {
//      fl = fr = true;
//      for (int j = i; j <= r; j++) {
//          if (tab ? A[j] < root : A[j] >= root) {
//              fr = false;
//              break;
//          }
//      }
//      for (int j = i - 1; j > l; j--) {
//          if (tab ? A[j] >= root : A[j] < root) {
//              fl = false;
//              break;
//          }
//      }
//      if (fr && fl) {
//          break;
//      }
//  }
//  pr(l + 1, i - 1, tab);
//  pr(i, r, tab);
//  printf(++cnt == 1 ? "%d" : " %d", root);
//}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 模拟