寻找子树

#include"BinaryTree.h"

bool DoesTree1HasTree2(BinaryTreeNode* pRoot1,BinaryTreeNode* pRoot2)
{
	if(pRoot2==NULL)
		return true;
	if(pRoot1==NULL)
		return false;
	if(pRoot1->m_nValue!=pRoot2->m_nValue)
		return false;
	return DoesTree1HasTree2(pRoot1->m_pLeft,pRoot2->m_pLeft)&&DoesTree1HasTree2(pRoot1->m_pRight,pRoot2->m_pRight);
}

bool HasSubTree(BinaryTreeNode* pRoot1,BinaryTreeNode* pRoot2)
{
	bool result=false;
	
	if(pRoot1!=NULL&&pRoot2!=NULL)
	{
		if(pRoot1->m_nValue==pRoot2->m_nValue)
			result=DoesTree1HasTree2(pRoot1,pRoot2);
		if(!result)
			result=HasSubTree(pRoot1->m_pLeft,pRoot2);
		if(!result)
			result=HasSubTree(pRoot1->m_pRight,pRoot2);
	}
	return result;
}
#include<iostream>
using namespace std;

struct BinaryTreeNode
{
	int m_nValue;
	BinaryTreeNode* m_pLeft;
	BinaryTreeNode* m_pRight;
};

BinaryTreeNode* insert(BinaryTreeNode** pRoot,int value)
{
	if(*pRoot==NULL)
	{
		*pRoot=new BinaryTreeNode;
		(*pRoot)->m_nValue=value;
		(*pRoot)->m_pLeft=NULL;
		(*pRoot)->m_pRight=NULL;
		return *pRoot;
	}
	if(value<(*pRoot)->m_nValue)
		(*pRoot)->m_pLeft=insert(&(*pRoot)->m_pLeft,value);
	else
		(*pRoot)->m_pRight=insert(&(*pRoot)->m_pRight,value);
	return *pRoot;
}


void printBinaryTree(BinaryTreeNode* pRoot)
{
	if(pRoot==NULL)
		return;
	cout<<pRoot->m_nValue<<" ";
	printBinaryTree(pRoot->m_pLeft);
	printBinaryTree(pRoot->m_pRight);
}	
<pre name="code" class="cpp">#include"HasSubTree.h"
#include<ctime>
#include<cstdlib>
int main()
{
	BinaryTreeNode* pRoot1=NULL;
	BinaryTreeNode* pRoot2=NULL;
	srand((unsigned int)(time(NULL)));
	for(int i=0;i<10;i++)
	{
		int randnum=rand()%100;
		insert(&pRoot1,randnum);
		if(i<3)
			insert(&pRoot2,randnum);
	}
	insert(&pRoot2,-1);
	cout<<"Tree1: ";
	printBinaryTree(pRoot1);
	cout<<endl;
	cout<<"Tree2: ";
	printBinaryTree(pRoot2);
	cout<<endl;
	if(HasSubTree(pRoot1,pRoot2))
		cout<<"Has Sub Tree"<<endl;
	else
		cout<<"Has No Sub Tree"<<endl;	
}


 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值