#include<iostream>
using namespace std;
struct BinaryTreeNode
{
double m_dbValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
bool DoesTree1HasTree2(BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2);
bool Equal(double num1, double num2);
bool HasSubTree(BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2)
{
bool result = false;
if (pRoot1 != nullptr && pRoot2 != nullptr)
{
if (Equal(pRoot1->m_dbValue, pRoot2->m_dbValue))
result = DoesTree1HasTree2(pRoot1, pRoot2);
if (!result)
result = HasSubTree(pRoot1->m_pLeft, pRoot2);
if (!result)
result = HasSubTree(pRoot1->m_pRight, pRoot2);
}
return result;
}
bool DoesTree1HasTree2(BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2)
{
if (pRoot2 == nullptr)
return true;
if (pRoot1 == nullptr)
return false;
if (!Equal(pRoot1->m_dbValue, pRoot2->m_dbValue))
return false;
return DoesTree1HasTree2(pRoot1->m_pLeft, pRoot2->m_pLeft) && DoesTree1HasTree2(pRoot1->m_pRight, pRoot2->m_pRight);
}
void creatTree(BinaryTreeNode* root, BinaryTreeNode* left, BinaryTreeNode* right)
{
root->m_pLeft = left;
root->m_pRight = right;
}
bool Equal(double num1, double num2)
{
if ((num1 - num2 > -0.0000001) && (num1 - num2 < 0.0000001))
return true;
else
return false;
}
int main()
{
BinaryTreeNode* root1 = new BinaryTreeNode();
root1->m_dbValue = 8;
root1->m_pLeft = nullptr;
root1->m_pRight = nullptr;
BinaryTreeNode* a = new BinaryTreeNode();
a->m_dbValue = 8;
a->m_pLeft = nullptr;
a->m_pRight = nullptr;
BinaryTreeNode* b = new BinaryTreeNode();
b->m_dbValue = 7;
b->m_pLeft = nullptr;
b->m_pRight = nullptr;
BinaryTreeNode* c = new BinaryTreeNode();
c->m_dbValue = 9;
c->m_pLeft = nullptr;
c->m_pRight = nullptr;
BinaryTreeNode* d = new BinaryTreeNode();
d->m_dbValue = 2;
d->m_pLeft = nullptr;
d->m_pRight = nullptr;
BinaryTreeNode* e = new BinaryTreeNode();
e->m_dbValue = 4;
e->m_pLeft = nullptr;
e->m_pRight = nullptr;
BinaryTreeNode* f = new BinaryTreeNode();
f->m_dbValue = 7;
f->m_pLeft = nullptr;
f->m_pRight = nullptr;
creatTree(root1, a, b);
creatTree(a, c, d);
creatTree(d, e, f);
BinaryTreeNode* root2 = new BinaryTreeNode();
root2->m_dbValue = 8;
root2->m_pLeft = nullptr;
root2->m_pRight = nullptr;
BinaryTreeNode* g = new BinaryTreeNode();
g->m_dbValue = 9;
g->m_pLeft = nullptr;
g->m_pRight = nullptr;
BinaryTreeNode* h = new BinaryTreeNode();
h->m_dbValue = 2;
h->m_pLeft = nullptr;
h->m_pRight = nullptr;
creatTree(root2, g, h);
bool result = HasSubTree(root1, root2);
cout << result << endl;
cin.get();
return 0;
}