小白專場-樹的同構-c語言實現.md

更新、更全的《數據結構與算法》的更新網站,更有python、go、人工智能教學等着你:http://www.javashuo.com/article/p-zfinzipt-hh.htmlpython

1、題意理解

給定兩棵樹T1和T2。若是T1能夠經過若干次左右孩子互換就變成T2,則咱們稱兩棵樹是「同構的」。現給定兩棵樹,請你判斷它們是不是同構的。算法

輸入格式:輸入給出2棵二叉樹的信息:數組

  • 先在一行中給出該樹的結點樹,隨後N行數據結構

  • 第i行對應編號第i個結點,給出該結點中存儲的字母、其左孩子結點的編號、右孩子結點的編號
  • 若是孩子結點爲空,則在相應位置給出「-」框架

以下圖所示,有多種表示的方式,咱們列出如下兩種:函數

2、求解思路

  1. 二叉樹表示
  2. 建二叉樹
  3. 同構判別

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 程序框架搭建

須要設計的函數:ui

  • 讀數據建二叉樹
  • 二叉樹同構判別
/* 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));
  }
}
相關文章
相關標籤/搜索