更新、更全的《數據結構與算法》的更新網站,更有python、go、人工智能教學等着你:https://www.cnblogs.com/nickchen121/p/11407287.html
一、題意理解
給定兩棵樹T1和T2。如果T1可以通過若干次左右孩子互換就變成T2,則我們稱兩棵樹是“同構的”。現給定兩棵樹,請你判斷它們是否是同構的。
輸入格式:輸入給出2棵二叉樹的信息:
-
先在一行中給出該樹的結點樹,隨后N行
-
第i行對應編號第i個結點,給出該結點中存儲的字母、其左孩子結點的編號、右孩子結點的編號
-
如果孩子結點為空,則在相應位置給出“-”
如下圖所示,有多種表示的方式,我們列出以下兩種:
二、求解思路
- 二叉樹表示
- 建二叉樹
- 同構判別
2.1 二叉樹表示
結構數組表示二叉樹:靜態鏈表
/* c語言實現 */
#define MaxTree 10
#define ElementType char
#define Tree int
#define Null -1
struct TreeNode
{
ElementType Element;
Tree Left;
Tree Right;
} T1[MaxTree], T2[MaxTree];
2.2 程序框架搭建
需要設計的函數:
- 讀數據建二叉樹
- 二叉樹同構判別
/* c語言實現 */
int main():
{
建二叉樹1;
建二叉樹2;
判別是否同構並輸出;
return 0;
}
int main()
{
Tree R1, R2;
R1 = BuildTree(T1);
R2 = BuildTree(T2);
if (Isomorphic(R1, R2)) printf("Yes\n");
else printf("No\n");
return 0;
}
2.3 如何建二叉樹
/* c語言實現 */
Tree BuildTree(struct TreeNode T[])
{
...;
scanf("%d\n", &N); // 輸入需要建立樹的長度
if (N) {
...;
for (i=0; i<N; i++) {
scanf("%c %c %c\n", &T[i].Element, &cl, &cr);
...;
}
...;
Root = ??? // 可以通過T[i]中沒有任何結點的left(cl)和right(cr)指向他這個條件獲取。
}
return Root;
}
/* c語言實現 */
Tree BuildTree(struct TreeNode T[])
{
...;
scanf("%d\n", &N); // 輸入需要建立樹的長度
if (N) {
for (i=0; i<N; i++) check[i] = 0;
for (i=0; i<N; i++) {
scanf("%c %c %c\n", &T[i].Element, &cl, &cr);
if (cl != '-'){
T[i].Left = cl-'0';
check[T[i].Left] = 1;
}
else T[i].Left = Null;
...; // 對cr的對應處理
}
for (i=0; i<N; i++)
if (!check[i]) break;
Root = i; // 可以通過T[i]中沒有任何結點的left(cl)和right(cr)指向他這個條件獲取。
}
return Root;
}
2.4 如何判別兩二叉樹同構
/* c語言實現 */
int Isomorphic(Tree R1, Tree R2)
{
if ((R1 == Null) && (R2 == Null)) // 左右子樹都為空
return 1;
if (((R1==Null)&&(R2!=Null)) || ((R1!=Null)&&(R2==Null)))
return 0; // 其中一顆子樹為空
if (T1[R1].Element != T2[R2].Element)
return 0; // 空結點為空
if ((T1[R1].Left == Null ) && ( T2[R2].Left == Null)) // 根的左右結點沒有子樹
return Isomorphic(T1[R1].Right, T2[R2].Right);
if (((T1[R1].Left != Null) && (T2[R2].Left!=Null)) &&
((T1[T1[R1].Left].Element) == (T2[T2[R2].Left].Element))) // 左右子樹不需要轉換
{
return (Isomorphic(T1[R1].Left, T2[R2].Left) &&
Isomorphic(T1[R1].Right, T2[R2].Right));
}
else { // 左右子樹需要轉換
return (Isomorphic(T1[R1].Left, T2[R2].Right) &&
Isomorphic(T1[R1].Right, T2[R2].Left));
}
}