# 二叉樹的同構

8
A 1 2
B 3 4
C 5 -
D - -
E 6 -
G 7 -
F - -
H - -
8
G - 4
B 7 6
F - -
A 5 1
H - -
C 0 -
D - -
E 2 -

Yes

8
B 5 7
F - -
A 0 3
C 6 -
H - -
D - -
G 4 -
E 1 -
8
D 6 -
B 5 -
E - -
H - -
C 0 2
G - 3
F - -
A 1 4

No

## C語言代碼

``````#include <stdio.h>
#include <stdlib.h>
#define maximum 10

typedef struct tnode
{
char data;
int lchildren;
int rchildren;
}tnode;
tnode tree1[maximum], tree2[maximum];

int build(tnode tree[])
{
int n;
scanf("%d\n", &n);
int i, check[n], root = -1;//check數組用於尋找根節點
char l, r;
for(i = 0; i < n; i++) check[i] = 0;
for(i = 0; i < n; i++)
{
scanf(" %c %c %c", &tree[i].data, &l, &r);
if(l != '-')
{
tree[i].lchildren = l - '0';
check[tree[i].lchildren] = 1;
}
else tree[i].lchildren = -1;
if(r != '-')
{
tree[i].rchildren = r - '0';
check[tree[i].rchildren] = 1;
}
else tree[i].rchildren = -1;
}
//尋找根節點，check數組的值爲零說明沒有雙親結點
for(i = 0; i < n; i++)
if(check[i] == 0)
{
root = i;
break;
}
return root;
}

int judge(int root1, int root2)
{
if((root1 == -1) && (root2 == -1)) return 1;//若根節點爲空，則同構
else if (root1 == -1 && root2 != -1 || root1 != -1 && root2 == -1) return 0;//根節點有一個爲空，另一個不空，非同構
else if (tree1[root1].data != tree2[root2].data) return 0;//根節點都不空但元素不同，非同構
//左子樹都爲空，則判斷右子樹
else if (tree1[root1].lchildren == -1 && tree2[root2].lchildren == -1) return judge(tree1[root1].rchildren, tree2[root2].rchildren);
//左子樹都不空且元素均相等，則判斷各子樹
else if (tree1[root1].lchildren != -1 && tree2[root2].lchildren != -1 && tree1[tree1[root1].lchildren].data == tree2[tree2[root2].lchildren].data)
return (judge(tree1[root1].lchildren, tree2[root2].lchildren) && judge(tree1[root1].rchildren, tree2[root2].rchildren));
//左子樹有一個爲空另一個不空 或者 左子樹都不空但元素不等，交換左右子樹
else return (judge(tree1[root1].lchildren, tree2[root2].rchildren) && judge(tree1[root1].rchildren, tree2[root2].lchildren));
}

int main(int argc, char *argv[]) {
int n, root1, root2;
root1 = build(tree1);
root2 = build(tree2);
if (judge(root1, root2)) printf("Yes");
else printf("No");
return 0;
}
``````