传送门:http://acm.hdu.edu.cn/showproblem.php?pid=3791

中文题不说题意。

建立完二叉搜索树后进行前序遍历或者后序遍历判断是否一样就可以了。

跟这次的作业第一题一模一样,输出输入改下就好

水的半死。

另外一题我以为是一定要一遍读入一边输出,被骗了,最后一起输出就好。等星期一再发那题的题解。

#include<cstdio>
#include<cstring>
int cur;
struct node
{
char c;
node *left,*right;
node() { left=right=NULL;}
}; struct Tree
{
node *root;
Tree() { root=NULL;} void insert(char x)
{
if(root==NULL)
{
root=new node;
root->left=root->right=NULL;
root->c=x;
return;
} node *p=root;
node *temp=new node;
temp->c=x;
while(true)
{
if(p->c > x) //left;
{
if(p->left!=NULL)
p=p->left;
else
{
p->left=temp;
return;
}
}
else if(p->c < x) //right
{
if(p->right!=NULL)
p=p->right;
else
{
p->right=temp;
return;
}
}
}
} void order(node *root,char *s) //后续前序均可,但中序遍历不可以。
{
if(root==NULL)
return; order(root->left,s);
order(root->right,s);
s[cur++]=root->c;
} }tree; int main()
{
int n;
while(scanf("%d",&n),n)
{
char s[12];
scanf("%s",s);
int len=strlen(s),i;
for(i=0;i<len;i++)
tree.insert(s[i]); char cmp[12];
char tcmp[12];
cur=0;
tree.order(tree.root,cmp);
cmp[cur]='\0';
for(i=0;i<n;i++)
{
cur=0;
tree.root=NULL;
scanf("%s",s);
int j;
for(j=0;j<len;j++)
tree.insert(s[j]); tree.order(tree.root,tcmp);
tcmp[cur]='\0';
printf("%s\n",(strcmp(cmp,tcmp)==0 ? "YES":"NO"));
}
tree.root=NULL;
}
}

附上这次作业原题:

数据结构与算法实验题 10.2 小明

★实验任务 

小明今天刚刚学会了搜索二叉树,不同的数字序列可能会得到同一棵搜索二叉树。为了更好的复习。小明先写一个数字序列,接着又写了 n 个数字序列,,他想知道这 n 个序列是否与第一个序列同属于一棵搜索二叉树,但他现在无法判断它们是否是同一棵搜索二叉树,所以他请你帮忙 

★数据输入 

 开始一个数 n,(1<=n<=20) 表示有 n 个需要判断, 接下去一行是一个序列,序列长度小于 10,包含(0~9)的数字,没有重复数字,根据这个序列可以构造出一颗二叉搜索树。 接下去的 n 行有 n 个序列,每个序列格式跟第一个序列一样,请判断这两个序列是否能组成同一颗二叉搜索树。 

★数据输出 

 对于这 n 个序列,如果与第一个序列是同一棵搜索二叉树,输出“Yes”,否则输出“No”。

就是上面的代码改改输入和输出的Yes和No和HDU那题不一样(HDU是YES和NO)

#include<cstdio>
#include<cstring>
int cur;
struct node
{
char c;
node *left,*right;
node() { left=right=NULL;}
}; struct Tree
{
node *root;
Tree() { root=NULL;} void insert(char x)
{
if(root==NULL)
{
root=new node;
root->left=root->right=NULL;
root->c=x;
return;
} node *p=root;
node *temp=new node;
temp->c=x;
while(true)
{
if(p->c > x) //left;
{
if(p->left!=NULL)
p=p->left;
else
{
p->left=temp;
return;
}
}
else if(p->c < x) //right
{
if(p->right!=NULL)
p=p->right;
else
{
p->right=temp;
return;
}
}
}
} void order(node *root,char *s) //后续前序均可,但中序遍历不可以。
{
if(root==NULL)
return; order(root->left,s);
order(root->right,s);
s[cur++]=root->c;
} }tree; int main()
{
int n;
scanf("%d",&n); char s[12];
scanf("%s",s);
int len=strlen(s),i;
for(i=0;i<len;i++)
tree.insert(s[i]); char cmp[12];
char tcmp[12];
cur=0;
tree.order(tree.root,cmp);
cmp[cur]='\0';
for(i=0;i<n;i++)
{
cur=0;
tree.root=NULL;
scanf("%s",s);
int j;
for(j=0;j<len;j++)
tree.insert(s[j]); tree.order(tree.root,tcmp);
tcmp[cur]='\0';
printf("%s\n",(strcmp(cmp,tcmp)==0 ? "Yes":"No"));
}
tree.root=NULL; }
04-05 02:39