题目:http://ac.jobdu.com/problem.php?pid=1009
/**************************************************
FileName: 九度1009.二叉搜索树
Author:3stone
Time:2017/2/25
题意:判断两序列是否构造出同一个二叉排序树
***************************************************/
#include<cstdio>
#include<cstring>
using namespace std;
struct Node {
Node *lchild;
Node *rchild;
int c;
}tree[220]; //最多20棵数,每棵树节点<=10
int loc = 0; //记录已使用的tree数组的下标
void postOrder(Node *T, int re[], int num) {//后序
if (T->lchild != NULL)
postOrder(T->lchild, re, num);
if (T->rchild != NULL)
postOrder(T->rchild, re, num);
re[num++] = T->c;//记录后序遍历所得序列
}
void inOrder(Node *T,int re[], int num) {//中序
if (T->lchild != NULL)
inOrder(T->lchild, re, num);
re[num++] = T->c;//记录中序遍历所得序列
if (T->rchild != NULL)
inOrder(T->rchild, re, num);
}
bool judge(int a[], int b[], int len) {//判断两数组是否相同
for (int i = 0; i < len; i++)
if (a[i] != b[i])
return false;
return true;
}
Node *creat() {//初始化 节点
tree[loc].lchild = tree[loc].rchild = NULL;
return &tree[loc++];
}
Node *insert(Node *T, int x) {//插入节点
if (NULL == T) {
T = creat();//初始化
T->c = x;
return T;
}
else if (x < T->c)
T->lchild = insert(T->lchild, x);
else if (x > T->c)
T->rchild = insert(T->rchild, x);
return T;
}
Node *creatTree(char str[]) { //构造二叉树
int len = strlen(str);
Node *T = creat();
T->c = str[0] - '0';
for (int i = 1; i < len; i++) { //依次插入
T = insert(T, str[i] - '0'); //始终返回根节点
}
return T;
}
int main() {
int n;
while (scanf("%d", &n) != EOF) {
if (0 == n) break;
loc = 0;
char first[10];
scanf("%s", first);
int len1 = strlen(first);
//构造1号树
Node *T_1 = creatTree(first);
//中序、后序遍历
int t1_in[12] = { 0 };
int t1_post[12] = { 0 };
inOrder(T_1, t1_in, 0);//t1_in记录中序遍历所得序列
postOrder(T_1, t1_post, 0);//t1_post记录后序遍历所得序列
char second[22][10];
for (int i = 0; i < n; i++) {
scanf("%s", second[i]);
int len2 = strlen(second[i]);
//构造2号树
Node *T_2 = creatTree(second[i]);
//中序、后序遍历
int t2_in[12] = { 0 };
int t2_post[12] = { 0 };
inOrder(T_2, t2_in, 0);
postOrder(T_2, t2_post, 0);
//比较 t1_in 和 t2_in t1_post 和 t2_post
if (len1==len2 && judge(t1_in,t2_in,len1)
&& judge(t1_post,t2_post,len1))
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}