因为存在二叉树节点的值全部相同的情况,所以要把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;
}