类型:二叉搜索树
题目:给定一个序列,构造一个二叉搜索树,然后对给定的其他序列和第一个序列相比,判断两个序列是否能组成同一颗二叉搜索树
按照第一个序列先构造一棵二叉搜索树,然后对其他序列,同样构造一棵二叉搜索树,如果两棵树相同,则其先序和后序序列相同,可以根据两棵树的先序和后序序列判断结果
// hdoj 3791 二叉搜索树
// tle wa wa wa ac
#include <iostream>
#include <string>
#include <cstdio>
using namespace std;
#define FOR(i,a,b) for(i = (a); i < (b); ++i)
#define FORE(i,a,b) for(i = (a); i <= (b); ++i)
const int MAXN = 20;
struct node {
char key;
node *lchild;
node *rchild;
};
node *T1, *T2;
int len, n;
char first[MAXN], last[MAXN], first1[MAXN], last1[MAXN];
string s0, s1;
void xianxu(node *T) {
first1[len++] = T->key;
if(T->lchild == NULL && T->rchild == NULL)
return ;
if(T->lchild != NULL)
xianxu(T->lchild);
if(T->rchild != NULL)
xianxu(T->rchild);
}
void houxu(node *T) {
if(T->lchild != NULL)
houxu(T->lchild);
if(T->rchild != NULL)
houxu(T->rchild);
last1[len++] = T->key;
}
void InsertBST(node* &T, char key) {
if(T == NULL) {
T = new node;
T->lchild = T->rchild = NULL;
T->key = key;
return;
}
if(key < T->key)
InsertBST(T->lchild, key);
else
InsertBST(T->rchild, key);
}
void solve() {
int i, j;
while(cin>>n, n) {
cin>>s0;
T1 = NULL;
FOR(i, 0, (int)(s0.length()))
InsertBST(T1, s0[i]);
len = 0;
xianxu(T1);
len = 0;
houxu(T1);
FOR(i, 0, (s0.length()))
first[i] = first1[i], last[i] = last1[i];
FOR(i, 0, n) {
cin>>s1;
T2 = NULL;
FOR(j, 0, (int)(s1.length()))
InsertBST(T2, s1[j]);
len = 0;
xianxu(T2);
len = 0;
houxu(T2);
FOR(j, 0, (s1.length()))
if(first[j] != first1[j] || last[j] != last1[j])
break;
if(j >= (int)(s1.length()))
cout<<"YES\n";
else
cout<<"NO\n";
}
}
}
int main()
{
solve();
return 0;
}
/*
1
1
1
2
123
123
123
5
123
321
132
213
312
123
*/