题目:请完成一个函数,输入一个二叉树,该函数输出它的镜像。
#include<iostream>
using namespace std;
struct BinaryTreeNode {
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
void MirrorOfBinaryTree(BinaryTreeNode* pRoot) {
//思路:遍历每个节点 交换该节点左右子树
if (pRoot == nullptr) {
return;
}
if (pRoot->m_pLeft == nullptr && pRoot->m_pRight == nullptr) {
return;
}
BinaryTreeNode* pTemp = pRoot->m_pLeft;
pRoot->m_pLeft = pRoot->m_pRight;
pRoot->m_pRight = pTemp;
if (pRoot->m_pLeft!=nullptr) {
MirrorOfBinaryTree(pRoot->m_pLeft);
}
if (pRoot->m_pRight != nullptr) {
MirrorOfBinaryTree(pRoot->m_pRight);
}
}
//测试代码==========================================================
BinaryTreeNode* CreateBinaryTreeNode(double nValue)
{
BinaryTreeNode* pNode = new BinaryTreeNode();
pNode->m_nValue = nValue;
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);
}
}
void PrintTree(BinaryTreeNode* pRoot) {
if (pRoot != nullptr) {
if (pRoot->m_pLeft != nullptr) {
PrintTree(pRoot->m_pLeft);
}
if (pRoot->m_pRight != nullptr) {
PrintTree(pRoot->m_pRight);
}
cout << pRoot->m_nValue << " ";
}
}
int main() {
BinaryTreeNode* pNode1 = CreateBinaryTreeNode(8);
BinaryTreeNode* pNode2 = CreateBinaryTreeNode(6);
BinaryTreeNode* pNode3 = CreateBinaryTreeNode(10);
BinaryTreeNode* pNode4 = CreateBinaryTreeNode(5);
BinaryTreeNode* pNode5 = CreateBinaryTreeNode(7);
BinaryTreeNode* pNode6 = CreateBinaryTreeNode(9);
BinaryTreeNode* pNode7 = CreateBinaryTreeNode(11);
ConnectTreeNodes(pNode1, pNode2, pNode3);
ConnectTreeNodes(pNode2, pNode4, pNode5);
ConnectTreeNodes(pNode3, pNode6, pNode7);
//PrintTree(pNode1);
MirrorOfBinaryTree(pNode1);
PrintTree(pNode1);
return 0;
}