剑指offer 面试题26 树的子结构

#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()
{
	/*       树1
	       root1(8)
       a(8)           b(7)
  c(9)       d(2)
         e(4)    f(7)
	
	
	         树2
			 root2(8)
	   g(8)          h(2)
	
	
	*/
	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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值