C++练习 | 递归判断二叉树是否同构

 1 #include <iostream>
 2 using namespace std;
 3 
 4 struct Tree
 5 {
 6     int data;
 7     Tree *lchild;
 8     Tree *rchild;
 9 }tree;
10 
11 Tree *Create(int a1[],int b1[],int n)
12 {
13     int k;
14     if(n<=0)
15         return NULL;
16     int root=a1[0];
17     Tree *bt=(Tree *)malloc(sizeof(Tree));
18     bt->data=root;
19     for(k=0;k<n;k++)
20     {
21         if(b1[k]==root)
22             break;//分割左右子树
23     }
24     bt->lchild=Create(a1+1,b1,k);
25     bt->rchild=Create(a1+k+1,b1+k+1,n-k-1);
26     return bt;
27 }
28 
29 int same(Tree *x1,Tree *x2)
30 {
31     if(x1->data!=x2->data)
32         return -1;
33     if(x1->data==x2->data)
34     {
35         if((x1->lchild==NULL&&x2->lchild==NULL)&&(x1->rchild!=NULL&&x2->rchild!=NULL))
36             return same(x1->rchild,x2->rchild);
37         if((x1->lchild!=NULL&&x2->lchild!=NULL)&&(x1->rchild==NULL&&x2->rchild==NULL))
38             return same(x1->lchild,x2->lchild);
39         if((x1->rchild!=NULL&&x2->rchild==NULL)||(x1->rchild==NULL&&x2->rchild!=NULL)||(x1->lchild!=NULL&&x2->lchild==NULL)||(x1->lchild==NULL&&x2->lchild!=NULL))
40             return -1;
41         if((x1->lchild==NULL&&x2->lchild==NULL)&&(x1->rchild==NULL&&x2->rchild==NULL))
42             return 1;
43         if((x1->lchild!=NULL&&x2->lchild!=NULL)&&(x1->rchild!=NULL&&x2->rchild!=NULL))
44             return (same(x1->rchild,x2->rchild)==1&&same(x1->lchild,x2->lchild)==1);
45     }
46     return 1;
47 }
48 
49 int main()
50 {
51     Tree *rt1,*rt2;
52     int is;
53     int a1[107],b1[107],a2[107],b2[107],N;//N为总节点数,a为先序序列,b为中序序列
54     cin>>N;
55     for(int i=0;i<N;i++)
56         cin>>a1[i];
57     for(int i=0;i<N;i++)
58         cin>>b1[i];
59     for(int i=0;i<N;i++)
60         cin>>a2[i];
61     for(int i=0;i<N;i++)
62         cin>>b2[i];
63     rt1=Create(a1,b1,N);//存树
64     rt2=Create(a2,b2,N);
65     is=same(rt1,rt2);
66     if(is==1)
67         cout<<"YES"<<endl;
68     else
69         cout<<"NO"<<endl;
70     return 0;
71 }

转载于:https://www.cnblogs.com/tsj816523/p/10650706.html

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值