#include<iostream>
#include <stdlib.h>
using namespace std;
struct node{
int data;
node* leftchild;
node* rightchild;
};
bool isSubtree(node* root1,node* root2){
if(root2==NULL)
return true;
if(root1==NULL)
return false;
if(root1->data==root2->data && isSubtree(root1->leftchild,root2->leftchild) &&
isSubtree(root1->rightchild,root2->rightchild))
return true;
if(isSubtree(root1->leftchild,root2)||isSubtree(root1->rightchild,root2))
return true;
else
return false;
}
struct node* newNode(int i){
struct node* node =
(struct node*)malloc(sizeof(struct node));
node->data=i;
node->leftchild=NULL;
node->rightchild=NULL;
return node;
}
int main(){
struct node *T = newNode(26);
T->rightchild = newNode(3);
T->rightchild->rightchild = newNode(3);
T->leftchild = newNode(10);
T->leftchild->leftchild = newNode(4);
T->leftchild->leftchild->rightchild= newNode(30);
T->leftchild->rightchild = newNode(6);
struct node *S = newNode(10);
S->rightchild = newNode(6);
S->leftchild = newNode(4);
if( isSubtree(T, S) )
printf("Tree S is subtree of tree T");
else
printf("Tree S is not a subtree of tree T");
getchar();
return 0;
}
转载于:https://my.oschina.net/zshuangyan/blog/173232