問題描述
給定兩棵樹T1和T2。如果T1可以通過若干次左右孩子互換就變成T2,則我們稱兩棵樹是“同構”的。
例如下圖給出的兩棵樹就是同構的,因爲我們把其中一棵樹的結點A、B、G的左右孩子互換後,就得到另外一棵樹。
這幅圖中的兩棵樹就不是同構的
現給定兩棵樹,請你判斷它們是否是同構的。
輸入格式
輸入給出2棵二叉樹樹的信息。對於每棵樹,首先在一行中給出一個非負整數N (≤10),即該樹的結點數(此時假設結點從0到N−1編號);隨後N行,第i行對應編號第i個結點,給出該結點中存儲的1個英文大寫字母、其左孩子結點的編號、右孩子結點的編號。如果孩子結點爲空,則在相應位置上給出“-”。給出的數據間用一個空格分隔。注意:題目保證每個結點中存儲的字母是不同的。
輸出格式
如果兩棵樹是同構的,輸出“Yes”,否則輸出“No”。
輸入樣例1(對應第一幅圖)
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 -
輸出樣例1
Yes
輸入樣例2(對應第二幅圖)
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
輸出樣例2
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;
}