#include <stdio.h>
#include <stdlib.h>
#define Null -1
typedef struct tree* Tree;
typedef struct node* Node;
struct tree{
int head;
Node TREE;
};
struct node{
char Letter;
int left;
int Right;
};
Tree Read(int N);
int IF(Tree A, Tree B);
int main(void){
int N;
Tree A,B;
scanf("%d\n",&N);
A=Read(N);
getchar();
scanf("%d\n",&N);
B=Read(N);
(IF(A,B))?printf("Yes"):printf("No");
return 0;
}
Tree Read(int N){
Tree A=(Tree)malloc(sizeof(struct tree));
if(N==0){
A->head=Null;
return A;
}
A->TREE=(Node)malloc(N*sizeof(struct node));
int i,n;
int a[N];
char ch,chL,chR;
for(i=0;i<N;i++){
scanf("%c %c %c",&ch,&chL,&chR);
if(i!=N-1) getchar();
A->TREE[i].Letter=ch;
if(chL=='-') A->TREE[i].left=Null;
else {
n=(int)(chL-'0');
A->TREE[i].left=n;
a[n]=1;
}
if(chR=='-') A->TREE[i].Right=Null;
else{
n=chR-'0';
A->TREE[i].Right=n;
a[n]=1;
}
}
for(i=0;i<N;i++){
if(a[i]!=1){
A->head=i;
break;
}
}
return A;
}
Tree sonL(Tree A){
Tree AL=(Tree)malloc(sizeof(struct tree));
AL->head=A->TREE[A->head].left;
AL->TREE=A->TREE;
return AL;
}
Tree sonR(Tree A){
Tree AR=(Tree)malloc(sizeof(struct tree));
AR->head=A->TREE[A->head].Right;
AR->TREE=A->TREE;
return AR;
}
int IF(Tree A, Tree B){
if(A->head==Null && B->head==Null) return 1;
if(A->head!=Null && B->head==Null) return 0;
if(A->head==Null && B->head!=Null) return 0;
if(A->TREE[A->head].Letter!=B->TREE[B->head].Letter) return 0;
Tree AL=sonL(A);
Tree AR=sonR(A);
Tree BL=sonL(B);
Tree BR=sonR(B);
if(IF(AL,BL) && IF(AR,BR)) return 1;
else if(IF(AL,BR) && IF(AR,BL)) return 1;
else return 0;
}
03-树1 树的同构
最新推荐文章于 2024-07-20 11:22:21 发布