03-树1 树的同构

#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;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值