给定两个二叉树T和S,判断S是否为T的子树

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

#include
#include 
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

你可能感兴趣的:(给定两个二叉树T和S,判断S是否为T的子树)