[Jobdu] 题目1520:树的子结构

题目描述:

输入两颗二叉树A,B,判断B是不是A的子结构。注:B为空树时不为任何树的子树

1 typedef struct BTNode{
2     int key;
3     struct BTNode *rchild;
4     struct BTNode *lchild;
5 }BTNode;

下面给出判断B树是A树的子结构的主要代码:

 1 bool compare(BTNode *t1, BTNode *t2) {
 2     if (!t2)
 3         return true;
 4     if (!t1)
 5         return false;
 6     if (t1->key != t2->key)
 7         return false;
 8     return compare(t1->lchild, t2->lchild) && compare(t1->rchild, t2->rchild);
 9 }
10 
11 bool isSubtree(BTNode *t1, BTNode *t2) {
12     bool flag = false;
13     if (t1 && t2) {
14         if (t1->key == t2->key)
15             flag = compare(t1, t2);
16         if (!flag)
17             flag = isSubtree(t1->lchild, t2);
18         if (!flag)
19             flag = isSubtree(t2->rchild, t2);
20     }
21 
22     return flag;
23 }
原文地址:https://www.cnblogs.com/tonyhu1993/p/4708447.html