树的子结构和树的深度

输入两棵二叉树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:
");
64     Createb(&root1);//生成二叉树
65     printf("create BSTree root2:
");
66     Createb(&root2);//生成二叉树
67     printf("root1's depth is:%d:
",TreeDepth(root1));
68     printf("root2's depth is:%d:
",TreeDepth(root2));
69     if(HaveSubtree(root1,root2))
70     printf("root2是root1的子结构!
");
71     else
72     printf("root2不是root1的子结构!
");   
73 }

打印结果:

原文地址:https://www.cnblogs.com/wxdjss/p/5450791.html