递归判断二叉树是否同构

 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 }

猜你喜欢

转载自www.cnblogs.com/tsj816523/p/10650706.html