额……说实话这题刚开始没看太明白,始终不知道该从那个点出发去想,后来请教了一下同学,然后又到网上找了一篇题解看看,算好明白了。
当时的疑惑有两个
q1:输入的一串数该如何写成二叉树的形式储存起来?
q2:如何比较两个二叉树是不是一样?
a1:依次读取每一位上的数,存进链表,如果当前的树是空的,则date=x;如果不为空,则判断x与date的值,如果x>date,往右边去,反之往左边去;
a2:讲链表正反各读一遍,存进字符串,比较两个字符串的值,如果相等则说明这两个树相等,否则这两个树不想等;
下面是代码
ps,当时写这道题的时候,指针因为好久不用已经晕了,所以在表头贴出来指针的一些声明和运算的方法;
/*
// 声明一个int指针
int *ptr;
// 声明一个int值
int val = 1;
// 为指针分配一个int值的引用
ptr = &val;
// 对指针进行取值,打印存储在指针地址中的内容
int deref = *ptr;
printf("%d\n", deref);
*/
//指针的使用;
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
#include<algorithm>
using namespace std;
struct node
{
int date;
node *lch,*rch;
};
char st[25],ss[25],f[25],ff[25],b[25],bb[25];
int cnt;
node *insert(node *p,int x)
{
if(p==NULL){
node *q=new node;//用new申请的变量记得最后释放
q->date=x;
q->lch=q->rch=NULL;
return q;
}
else{
if(x<p->date)
p->lch=insert(p->lch,x);
else
p->rch=insert(p->rch,x);
return p;
}
}
void p1(node *L,char f[])
{
if(L)
{
f[cnt++]=L->date+'0';
p1(L->lch,f);
p1(L->rch,f);
}
}
void p2(node *L,char b[])
{
if(L)
{
p2(L->lch,b);
p2(L->rch,b);
b[cnt++]=L->date+'0';
}
}
int main()
{
int i,j;
int n;
while(scanf("%d",&n)==1&&n)
{
node *L1=NULL;//第一次错误忘记初始化,导致程序崩溃;
node *L2=NULL;
scanf("%s", st);
int c=strlen(st);
for(i=0; i<c; i++)
L1=insert(L1,st[i]-'0');
cnt=0;
p1(L1,f);
f[cnt]=0;
cnt=0;
p2(L1,b);
b[cnt]=0;
while(n--)
{
scanf("%s",ss);
int c=strlen(ss);
for(i=0; i<c; i++)
L2=insert(L2,ss[i]-'0');
cnt=0;
p1(L2,ff);
ff[cnt]=0;
cnt=0;
p2(L2,bb);
bb[cnt]=0;
if(strcmp(f,ff)==0 && strcmp(b,bb)==0)
printf("YES\n");
else
printf("NO\n");
free(L2);//使用完变量之后要记得释放内存,并且将变量初始化
L2=NULL;
}
free(L1);
L1=NULL;
}
return 0;
}