#include"BinaryTree.h"
void MirrorRecursively(BinaryTreeNode* pNode)
{
if(pNode==NULL||pNode->m_pLeft==NULL&&pNode->m_pRight==NULL)
return;
BinaryTreeNode *pTemp=pNode->m_pLeft;
pNode->m_pLeft=pNode->m_pRight;
pNode->m_pRight=pTemp;
if(pNode->m_pLeft)
MirrorRecursively(pNode->m_pLeft);
if(pNode->m_pRight)
MirrorRecursively(pNode->m_pRight);
}
<pre name="code" class="cpp">#include<iostream>
using namespace std;
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* m_pLeft;
BinaryTreeNode* m_pRight;
};
BinaryTreeNode* insert(BinaryTreeNode** pRoot,int value)
{
if(*pRoot==NULL)
{
*pRoot=new BinaryTreeNode;
(*pRoot)->m_nValue=value;
(*pRoot)->m_pLeft=NULL;
(*pRoot)->m_pRight=NULL;
return *pRoot;
}
if(value<(*pRoot)->m_nValue)
(*pRoot)->m_pLeft=insert(&(*pRoot)->m_pLeft,value);
else
(*pRoot)->m_pRight=insert(&(*pRoot)->m_pRight,value);
return *pRoot;
}
void printBinaryTree(BinaryTreeNode* pRoot)
{
if(pRoot==NULL)
return;
cout<<pRoot->m_nValue<<" ";
printBinaryTree(pRoot->m_pLeft);
printBinaryTree(pRoot->m_pRight);
}
<pre name="code" class="cpp">#include"MirrorRecursively.h"
#include<ctime>
#include<cstdlib>
int main()
{
BinaryTreeNode* pRoot1=NULL;
srand((unsigned int)(time(NULL)));
for(int i=0;i<10;i++)
{
int randnum=rand()%100;
insert(&pRoot1,randnum);
}
cout<<"Tree1: ";
printBinaryTree(pRoot1);
cout<<endl;
MirrorRecursively(pRoot1);
cout<<"Mirror: ";
printBinaryTree(pRoot1);
cout<<endl;
}