题目要求:给定两个非空二叉树s和t,检查s中是否包含和t具有相同结构和节点值的子树。s的一个子树包括s的一个节点和这个节点的所有子孙,s也可看做它自身的一棵子树
bool isSame(Node *p1, Node *p2){
if (p1 == NULL&&p2 == NULL){
return true;
}
if (p1 == NULL || p2 == NULL){
return false;
}
return
p1->value == p1->value &&
isSame(p1->left, p2->left) &&
isSame(p1->right, p2->right);
}
//前序遍历
bool preOrder(Node *root, Node *t){
if (root != NULL){
//根
if (isSame(root, t)){//找到子树
return true;
}
if (preOrder(root->left, t) == true){//如果在左子树里面找到了,就不需要去右子树里面找
return true;
}
return preOrder(root->left,t);
}
return false;
}
//是否为另一个的子树
bool isSubtree(Node *s, Node *t){
return preOrder(s, t);//根据前序的结果决定我的结果
}
void test(){
Node *root=CreatTree();
Node *e=CreatNode('E');
Node *h=CreatNode('H');
Node *i=CreatNode('I');
e->left=NULL;
e->right=h;
h->right=i;
if( isSubtree(root,e)){
printf("是子树\n");
}
else{
printf("不是子树\n");
}