题目:请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
#include<iostream>
using namespace std;
struct BinaryTreeNode {
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
//思路:对称树的前序遍历和对称前序遍历相同
bool IsSymmetrical(BinaryTreeNode* pRoot1, BinaryTreeNode* pRoot2) {
if (pRoot1 == nullptr && pRoot2 == nullptr) {
return true;
}
if (pRoot1 == nullptr || pRoot2 == nullptr) {
return false;
}
if (pRoot1->m_nValue != pRoot2->m_nValue) {
return false;
}
return IsSymmetrical(pRoot1->m_pLeft, pRoot2->m_pRight) && IsSymmetrical(pRoot1->m_pRight, pRoot2->m_pLeft);
}
//测试补充代码
BinaryTreeNode* CreateBinaryTreeNode(double dbValue)
{
BinaryTreeNode* pNode = new BinaryTreeNode();
pNode->m_nValue = dbValue;
pNode->m_pLeft = nullptr;
pNode->m_pRight = nullptr;
return pNode;
}
void ConnectTreeNodes(BinaryTreeNode* pParent, BinaryTreeNode* pLeft, BinaryTreeNode* pRight)
{
if (pParent != nullptr)
{
pParent->m_pLeft = pLeft;
pParent->m_pRight = pRight;
}
}
void DestroyTree(BinaryTreeNode* pRoot)
{
if (pRoot != nullptr)
{
BinaryTreeNode* pLeft = pRoot->m_pLeft;
BinaryTreeNode* pRight = pRoot->m_pRight;
delete pRoot;
pRoot = nullptr;
DestroyTree(pLeft);
DestroyTree(pRight);
}
}
int main() {
BinaryTreeNode* pNode8 = CreateBinaryTreeNode(8);
BinaryTreeNode* pNode61 = CreateBinaryTreeNode(6);
BinaryTreeNode* pNode62 = CreateBinaryTreeNode(6);
BinaryTreeNode* pNode51 = CreateBinaryTreeNode(5);
BinaryTreeNode* pNode71 = CreateBinaryTreeNode(7);
BinaryTreeNode* pNode72 = CreateBinaryTreeNode(7);
BinaryTreeNode* pNode52 = CreateBinaryTreeNode(5);
ConnectTreeNodes(pNode8, pNode61, pNode62);
ConnectTreeNodes(pNode61, pNode51, pNode71);
ConnectTreeNodes(pNode62, pNode72, pNode52);
bool res = IsSymmetrical(pNode8, pNode8);
DestroyTree(pNode8);
return 0;
}