#include <cstdio>
#define nullptr NULL
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
BinaryTreeNode* CreateBinaryTreeNode(int value)
{
BinaryTreeNode* pNode = new BinaryTreeNode();
pNode->m_nValue = value;
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);
}
}
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_nValue != pRoot2->m_nValue)
return false;
return isSymmetrical(pRoot1->m_pLeft, pRoot2->m_pRight)
&& isSymmetrical(pRoot1->m_pRight, pRoot2->m_pLeft);
}
void main()
{
BinaryTreeNode* pNode8 = CreateBinaryTreeNode(8);
BinaryTreeNode* pNode61 = CreateBinaryTreeNode(6);
BinaryTreeNode* pNode9 = CreateBinaryTreeNode(6);
BinaryTreeNode* pNode51 = CreateBinaryTreeNode(5);
BinaryTreeNode* pNode71 = CreateBinaryTreeNode(7);
BinaryTreeNode* pNode72 = CreateBinaryTreeNode(7);
BinaryTreeNode* pNode52 = CreateBinaryTreeNode(5);
ConnectTreeNodes(pNode8, pNode61, pNode9);
ConnectTreeNodes(pNode61, pNode51, pNode71);
ConnectTreeNodes(pNode9, pNode72, pNode52);
if(isSymmetrical( pNode8))
printf("是对称的二叉树\n");
DestroyTree(pNode8);
}
剑指offer--面试题28:对称的二叉树
最新推荐文章于 2017-07-25 10:05:13 发布