- 题目描述:
-
输入两颗二叉树A,B,判断B是不是A的子结构。注:B为空树时不为任何树的子树
typedef struct BTNode{
int key;
struct BTNode *rchild;
struct BTNode *lchild;
}BTNode;
下面给出判断B树是A树的子结构的主要代码:
bool compare(BTNode *t1, BTNode *t2) {
if (!t2)
return true;
if (!t1)
return false;
if (t1->key != t2->key)
return false;
return compare(t1->lchild, t2->lchild) && compare(t1->rchild, t2->rchild);
} bool isSubtree(BTNode *t1, BTNode *t2) {
bool flag = false;
if (t1 && t2) {
if (t1->key == t2->key)
flag = compare(t1, t2);
if (!flag)
flag = isSubtree(t1->lchild, t2);
if (!flag)
flag = isSubtree(t2->rchild, t2);
} return flag;
}