HDU 3791 二叉搜索树
判断两序列是否为同一二叉搜索树序列
Input
开始一个数n,(1<=n<=20) 表示有n个需要判断,n= 0 的时候输入结束。
接下去一行是一个序列,序列长度小于10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。
接下去的n行有n个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。
Output
如果序列相同则输出YES,否则输出NO
Sample Input
2
567432
543267
576342
0
Sample Output
YES
NO
**题解:**建立搜索树,遍历比较即可
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cctype>
#include<iomanip>
#include<map>
#include<vector>
#include<list>
#include<deque>
#include<stack>
#include<queue>
#include<set>
#include<cctype>
#include<string>
#include<stdexcept>
#include<fstream>
#define mem(a,b) memset(a,b,sizeof(a))
#define mod 10000007
#define debug() puts("what the fuck!")
#define dedebug() puts("what the fuck!!!")
#define ll long long
#define speed {
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); };
using namespace std;
const double PI = acos(-1.0);
const int maxn = 1e6 + 120;
const int INF = 0x3f3f3f3f;
const double esp_0 = 1e-6;
int gcd(int x, int y) {
return y ? gcd(y, x % y) : x;
}
int a[maxn], b[maxn], k = 0;
typedef struct Tree* tree;
typedef struct Tree {
int data;
tree l, r;
};
tree root;
tree build(tree root, int x) {
if (root == NULL) {
root = (tree)malloc(sizeof(struct Tree));
root->data = x;
root->l = root->r = NULL;
}
else {
if (x <= root->data)root->l = build(root->l, x);
else root->r = build(root->r, x);
}
return root;
}
void preorder(tree root) {
if (root) {
a[k++] = root->data;
preorder(root->l);
preorder(root->r);
}
}
vector<int>v[maxn];
void dfs(tree root, int deep) {
//层序遍历
if (root == NULL)return;
v[deep].push_back(root->data);
dfs(root->l, deep + 1);
dfs(root->r, deep + 1);
}
int main() {
speed;
int n;
string s;
while (cin >> n, n) {
root = NULL;
k = 0;
cin >> s;
for (int i = 0; i < s.size(); ++i) {
int temp = s[i] - '0';
root = build(root, temp);
}
preorder(root);
//dfs(root, 0);
//for (int i = 0; i < s.size(); ++i) {
// for (int j = 0; j < v[i].size(); ++j) {
// cout << v[i][j] << " ";
// }
//}
//cout << endl;
for (int i = 0; i < s.size(); ++i) {
b[i] = a[i];
}
//for (int i = 0; i < s.size(); ++i)cout << b[i] << " ";
//cout << endl;
while (n--) {
k = 0;
root = NULL;
cin >> s;
for (int i = 0; i < s.size(); ++i) {
int temp = s[i] - '0';
root = build(root, temp);
}
preorder(root);
//for (int i = 0; i < s.size(); ++i)cout << a[i] << " ";
//cout << endl;
int i;
for (i = 0; i < s.size(); ++i) {
if (a[i] != b[i]) {
cout << "NO" << endl;
break;
}
}
if (i >= s.size())cout << "YES" << endl;
}
}
return 0;
}