因为最近在学数据结构,所以这道题用建树的方法做的,比较麻烦,但对于理解二叉搜索树很有帮助。
搜索二叉树要么是空树要么是符合以下性质的二叉树:
任意节点的左子树不空,则左子树上所有结点的值均小于它的根结点的值;
任意节点的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
任意节点的左、右子树也分别为二叉查找树,没有键值相等的节点。
根据题意,做这道题时分为建树(根据定义直接建),建树,判断比较(先判断长度,再判断是否都有子节点,再判断值是否一样),输出结果,删除建好的树下次再用,循环。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
int ct;
struct node
{
char val;
node *left,*right;
};
node* minsert(node *root, char val)
{
if (!root)
{
root = new node();
root->val = val;
}
else if (root->val < val)
{
root->right = minsert(root->right, val);
}
else if (root->val > val)
{
root->left = minsert(root->left, val);
}
return root;
}
void Delete(node* root)
{
if(root==NULL)
return;
Delete(root->left);
Delete(root->right);
delete root;
root=NULL;
return;
}
void judge(node *roo,node *rooo)
{
if((roo&&!rooo)||(!roo&&rooo))
{
ct = 0;
return;
}
if(roo && rooo)
{
judge(roo->left,rooo->left);
if(roo->val != rooo->val)
{
ct = 0;
return;
}
judge(roo->right,rooo->right);
}
}
int main()
{
int n;
while(scanf("%d",&n) != EOF && n!=0)
{
node *rt=NULL, *roo=NULL;
char a[11];
memset(a,0,sizeof(a));
int len1;
scanf("%s",a);
len1 = strlen(a);
for(int i=0; i<len1; i++)
{
rt = minsert(rt,a[i]);
if(i==0)
roo = rt;
}
for(int i=0; i<n; i++)
{
node *rtt=NULL, *rooo=NULL;
char b[11];
memset(a,0,sizeof(b));
int len2;
ct = 1;
scanf("%s",b);
len2 = strlen(b);
if(len1 != len2)
{
printf("NO\n");
break;
}
for(int j=0; j<len2; j++)
{
rtt = minsert(rtt,b[j]);
if(j == 0)
rooo = rtt;
}
judge(roo,rooo);
if(ct)
printf("YES\n");
else
printf("NO\n");
Delete(rooo);
}
Delete(roo);
}
return 0;
}
在网上搜别人的做法后发现这道题因为数据量不大的原因,用数组模拟二叉树做更简单一些,代码很好理解。
#include <iostream>
#include <string.h>
using namespace std;
const int N=10005;
char list1[N];
char bt1[N];
void create(char lis[],char bt[],int n)
{
int order;
bt[1]=lis[0];
for(int i=1; i<n; i++)
{
order=1;
while(bt[order]!='a')
{
if(lis[i]<bt[order])
order*=2;
else
order=order*2+1;
}
bt[order]=lis[i];
}
}
int main()
{
int n;
while(cin>>n&&n)
{
cin>>list1;
memset(bt1,'a',N);
create(list1,bt1,strlen(list1));
while(n--)
{
char list2[N];
cin>>list2;
char bt2[N];
memset(bt2,'a',N);
create(list2,bt2,strlen(list2));
if(strcmp(bt1,bt2)==0)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
}
}