#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;
}