標籤:
輸入兩棵二叉樹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
列印結果:
樹的子結構和樹的深度