核心是任意两种包括中序遍历的遍历结果相同,则树相同
理解了一点指针的用法
#include<iostream>
#include<string.h>
using namespace std;
struct Node{
Node* lch;
Node* rch;
int num;
}tree[110];
int k,l;
Node* create()
{
tree[l].lch = tree[l].rch = NULL;
return &tree[l++];
}
Node* insert(int c,Node *t){
if (t == NULL)
{
t = create();
t->num = c;
return t;
}
else if (c >= t->num)
{
t->rch = insert(c, t->rch);
}
else if (c < t->num)
{
t->lch = insert(c, t->lch);
}
return t;
}
char str1[25], str2[25];//字符串前序遍历和中序遍历字符串的链接
int size1, size2;
char *str;
int *size;
//中序遍历
void midOrder(Node *t)
{
if (t->lch != NULL)
midOrder(t->lch);
str[(*size)++] = t->num + '0';
if (t->rch != NULL)
midOrder(t->rch);
}
//后序遍历
void postOrder(Node* t)
{
if (t->lch != NULL)
postOrder(t->lch);
if (t->rch != NULL)
postOrder(t->rch);
str[(*size)++] = t->num+'0';
}
int main(){
int n;
char tmp[12];
while (cin >> n)
{
if (n == 0)
return 0;
cin >> tmp;
Node*T = NULL;
l = 0;
for (int i = 0; tmp[i]!=0; i++)
{
T = insert(tmp[i]-'0', T);
}
size1 = 0;
str = str1;
size = &size1;
midOrder(T);
postOrder(T);
str1[size1] = '\0';
while (n--)
{
cin >> tmp;
Node *T1 = NULL;
for (int i = 0;tmp[i]!=0; i++)
T1 = insert(tmp[i] - '0', T1);
size2 = 0;
size = &size2;
str = str2;
midOrder(T1);
postOrder(T1);
str2[size2] = '\0';
if (strcmp(str1, str2) == 0)
puts("yes");
else puts("no");
}
}
return 0;
}