标签:
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
typedef struct Node
{
Node *l,*r;
int num;
}*tree;
char f1[11],f2[11],l1[11],l2[11];
int cnt;
void insert(tree *T,int num) //创建二叉树
{
if ((*T) != NULL)
{
if (num < (*T)->num)
{
insert(&(*T)->l,num);
}
else
insert(&(*T)->r,num);
}
else
{
*T = (tree)malloc(sizeof(Node));
(*T)->num = num;
(*T)->l = NULL;
(*T)->r = NULL;
}
}
//
// void insert(tree T,int num) //创建二叉树
// {
// if ((T) != NULL)
// {
// if (num < (T)->num)
// {
// insert(T->l,num);
// }
// else
// insert(T->r,num);
// }
// else
// {
// T = (tree)malloc(sizeof(Node));
// T->num = num;
// T->l = NULL;
// T->r = NULL;
// }
// }
void pre_order(tree T,char f[]) //先序遍历,将遍历后的数据存在f数组中
{
if (T)
{
f[cnt++] = T->num + '0';
pre_order(T->l,f);
pre_order(T->r,f);
}
}
void post_order(tree T,char f[]) //后序遍历
{
if (T)
{
pre_order(T->l,f);
pre_order(T->r,f);
f[cnt++] = T->num + '0';
}
}
int main()
{
int n,i,k;
string str;
tree T=NULL;
tree T1=NULL;
while (cin>>n,n)
{
cin>>str;
for (i=0;i<str.length();i++)
{
insert(&T,str[i]-'0');
}
cnt = 0;
pre_order(T,f1);
f1[cnt] = 0; //易错点
cnt = 0;
post_order(T,l1);
l1[cnt] = 0;
for (i=0;i<n;i++)
{
cin>>str;
memset(f2,0,sizeof(f2));
memset(l2,0,sizeof(l2));
for (k=0;k<str.length();k++)
{
insert(&T1,str[k]-'0');
}
cnt = 0;
pre_order(T1,f2);
f2[cnt] = 0;
cnt = 0;
post_order(T1,l2);
l2[cnt] = 0;
if (strcmp(f1,f2) != 0 || strcmp(l1,l2) != 0)
{
cout<<"NO"<<endl;
}
else
cout<<"YES"<<endl;
free(T1);
T1=NULL;
}
free(T);
T=NULL;
}
return 0;
}
先创建树,再根据先序遍历与后序遍历是否都相等,相等则为同一树,反之,不同
insert函数的参数要注意引用,,,有关引用不是很懂。求大神给本菜鸟讲讲
第二种方法是用:数组创建树。
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
char tree1[1100],tree2[3000],tree3[3000];
void buildtree(char *temtree,int pos,char data)
{
if (temtree[pos] == '.')
{
temtree[pos] = data;
return ;
}
if (temtree[pos] < data)
{
buildtree(temtree,pos*2+1,data);
}
else
if (temtree[pos] > data)
{
buildtree(temtree,pos*2,data);
}
}
int main()
{
int n,i,k;
while (cin>>n,n)
{
memset(tree2,'.',sizeof(tree2));
cin>>tree1;
for (i=0;i<strlen(tree1);i++)
{
buildtree(tree2,1,tree1[i]);
}
for (i=0;i<n;i++)
{
cin>>tree1;
memset(tree3,'.',sizeof(tree3)); //易错点
for (k=0;k<strlen(tree1);k++)
{
buildtree(tree3,1,tree1[k]);
}
if (strcmp(tree2,tree3))
{
cout<<"NO"<<endl;
}
else
cout<<"YES"<<endl;
}
}
return 0;
}
标签:
原文地址:http://blog.csdn.net/xinwen1995/article/details/45479485