码迷,mamicode.com
首页 > 其他好文 > 详细

二叉树的子结构

时间:2014-07-31 13:35:56      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:二叉树的子结构

bubuko.com,布布扣

主要通过递归完成:

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;

}

运行结果:

bubuko.com,布布扣

二叉树的子结构,布布扣,bubuko.com

二叉树的子结构

标签:二叉树的子结构

原文地址:http://blog.csdn.net/buyingfei8888/article/details/38312167

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!