首页 > 代码库 > 二叉树的子结构

二叉树的子结构

主要通过递归完成:

1 根节点是否相同,不相同,进行第一次递归

2 根节点相同,在另外一个函数进行递归,判断子节点是否相同

#include <iostream>
#include <stack>
using namespace std;

 typedef struct tree{
	int key;
	struct	tree *left;
	struct	tree *right;
 } * pTree,Tree;


 void createTree(pTree & phead){
	int temp;
	scanf("%d",&temp);
	if(temp!=0){
		phead=(pTree)malloc(sizeof(Tree));
		phead->key=temp;
		createTree(phead->left);
		createTree(phead->right);
	}else{
		phead=NULL;
	}
 }
 void print(const pTree phead){
	 if(phead){
		printf("%d ",phead->key);
		print(phead->left);
		print(phead->right);
	 }
 }

 bool hasSub(pTree phead1,pTree phead2){
	bool result = false;

	if(phead2 ==  NULL)  //必须先判断phead2 再判断phead1  注意
	return true;

	if(phead1 == NULL)
		return false;

	if(phead1->key != phead2->key)
		return false;

	 return hasSub(phead1->left,phead2->left)  && 
		  hasSub(phead1->right,phead2->right);
		   
 }

bool hasSubTree(const pTree phead1,const pTree phead2){
	bool result=false;
	if( phead1 != NULL && phead2 != NULL){
		if(phead1->key==phead2->key)
			result=hasSub(phead1,phead2);
		if(!result)
    		result=	hasSubTree(phead1->left,phead2);
		if(!result)
    		result=	hasSubTree(phead1->right,phead2);

	}

	return result;
 }

int main(){
	pTree pHead1=NULL;
	pTree pHead2=NULL;

	createTree(pHead1);
	//createTree(pHead2);
	print(pHead1);
	cout<<endl;

	createTree(pHead2);
	print(pHead2);
	cout<<endl;

	cout<<(bool)hasSubTree(pHead1,pHead2);

	return 0;

}

运行结果: