剑指offer 面试题28 对称的二叉树

因为存在二叉树节点的值全部相同的情况,所以要把nullptr考虑进去

#include<iostream>

using namespace std;

struct BinaryTreeNode
{
	double m_dbValue;
	BinaryTreeNode* m_pLeft;
	BinaryTreeNode* m_pRight;
};

bool isSymmetrical(BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2);

bool isSymmetrical(BinaryTreeNode* pRoot)
{
	return isSymmetrical(pRoot,pRoot);
}

bool isSymmetrical(BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2)
{
	if (pRoot1 == nullptr && pRoot2 == nullptr)
		return true;
	if (pRoot1 == nullptr || pRoot2 == nullptr)
		return false;
	if (pRoot1->m_dbValue != pRoot2->m_dbValue)
		return false;

	return isSymmetrical(pRoot1->m_pLeft, pRoot2->m_pRight) && isSymmetrical(pRoot1->m_pRight, pRoot2->m_pLeft);
}



void creatTree(BinaryTreeNode* root, BinaryTreeNode* left, BinaryTreeNode* right)
{
	root->m_pLeft = left;
	root->m_pRight = right;
}


int main()
{

	/*       树1
	       root1(8)
       a(6)             b(6)
  c(5)      d(7)    e(7)    f(5)
         
	*/
	BinaryTreeNode* root1 = new BinaryTreeNode();
	root1->m_dbValue = 8;
	root1->m_pLeft = nullptr;
	root1->m_pRight = nullptr;

	BinaryTreeNode* a = new BinaryTreeNode();
	a->m_dbValue = 6;
	a->m_pLeft = nullptr;
	a->m_pRight = nullptr;

	BinaryTreeNode* b = new BinaryTreeNode();
	b->m_dbValue = 6;
	b->m_pLeft = nullptr;
	b->m_pRight = nullptr;

	BinaryTreeNode* c = new BinaryTreeNode();
	c->m_dbValue = 5;
	c->m_pLeft = nullptr;
	c->m_pRight = nullptr;

	BinaryTreeNode* d = new BinaryTreeNode();
	d->m_dbValue = 7;
	d->m_pLeft = nullptr;
	d->m_pRight = nullptr;

	BinaryTreeNode* e = new BinaryTreeNode();
	e->m_dbValue = 7;
	e->m_pLeft = nullptr;
	e->m_pRight = nullptr;

	BinaryTreeNode* f = new BinaryTreeNode();
	f->m_dbValue = 5;
	f->m_pLeft = nullptr;
	f->m_pRight = nullptr;

	creatTree(root1, a, b);
	creatTree(a, c, d);
	creatTree(b, e, f);

	
	bool result = isSymmetrical(root1);
	cout << result << endl;


	cin.get();
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值