二叉树的子结构

主要通过递归完成:

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;

}

运行结果:


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值