樹的子結構和樹的深度

來源:互聯網
上載者:User

標籤:

輸入兩棵二叉樹A和B,判斷B是不是A的子結構,同時求樹的深度。

 1 #include<iostream> 2 using namespace std; 3  4 typedef struct node 5 { 6 char data;//結點資料 7 struct node *lchild,*rchild;//二叉樹結點類型 8 }BSTree;//二叉樹結點類型 9 10 11 void Createb(BSTree **p)//建立二叉樹12 {13     char ch;14     cin>>ch;15     if(ch!=‘.‘)16     {17         *p=(BSTree*)malloc(sizeof(BSTree));//申請空間18         (*p)->data=ch;//空間賦值19         Createb(&(*p)->lchild);//產生左子樹20         Createb(&(*p)->rchild);//產生右子樹21     }22     else *p=NULL;//空結點23 }24 25 bool DoesTree1HaveTree2(BSTree *root1,BSTree *root2)26 {27     if(root2==NULL)28         return true;29     if(root1==NULL)30         return false;31     if(root1->data!=root2->data)32         return false;33     return DoesTree1HaveTree2(root1->lchild,root2->lchild)&&34            DoesTree1HaveTree2(root1->rchild,root2->rchild);35 }36 37 bool HaveSubtree(BSTree *root1,BSTree *root2)//判斷root2是否是root1的子結構38 {39     bool result=false;40     if(root1!=NULL&&root2!=NULL)41     {42         if(root1->data==root2->data)43             result=DoesTree1HaveTree2(root1,root2);44         if(!result)45             result= HaveSubtree(root1->lchild,root2);46         if(!result)47             result= HaveSubtree(root1->rchild,root2);48     }49     return result;50 }51 int TreeDepth(BSTree *root)//樹的深度52 {53     if(root==NULL)54         return 0;55     int left=TreeDepth(root->lchild);56     int right=TreeDepth(root->rchild);57     return (left>right) ? (left+1) : (right+1);58 }59 60 void main()61 {62     BSTree *root1,*root2;//二叉樹根指標63     printf("create BSTree root1:\n");64     Createb(&root1);//產生二叉樹65     printf("create BSTree root2:\n");66     Createb(&root2);//產生二叉樹67     printf("root1‘s depth is:%d:\n",TreeDepth(root1));68     printf("root2‘s depth is:%d:\n",TreeDepth(root2));69     if(HaveSubtree(root1,root2))70     printf("root2是root1的子結構!\n");71     else72     printf("root2不是root1的子結構!\n");   73 }
Code

列印結果:

 

樹的子結構和樹的深度

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.