//二叉树的镜像变换
#include <iostream>
#include <stack>
using namespace std;
//二叉树结构
struct BTreeNode
{
int m_nValue;
BTreeNode *m_pLeft;
BTreeNode *m_pRight;
};
//递归实现
void MirrorRecursively(BTreeNode *pNode)
{
if(!pNode)
{
return;
}
//交换左右孩子
BTreeNode *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);
}
}
void MirrorIteratively(BTreeNode *pNode)
{
if(!pNode)
{
return ;
}
stack<BTreeNode *> stackTreeNode;
stackTreeNode.push(pNode);
while(stackTreeNode.size())
{
BTreeNode *pNode = stackTreeNode.top();
stackTreeNode.pop();
//交换左右孩子
BTreeNode *pTemp = pNode->m_pLeft;
pNode->m_pLeft = pNode->m_pRight;
pNode->m_pRight = pTemp;
if(pNode->m_pLeft)
{
stackTreeNode.push(pNode->m_pLeft);
}
if(pNode->m_pRight)
{
stackTreeNode.push(pNode->m_pRight);
}
}
}
//按照先序创建二叉树,0表示空
BTreeNode *Create()
{
int ch;
cin>> ch;
if(ch == 0)
{
return NULL;
}
else
{
BTreeNode *root = new BTreeNode();
root->m_nValue = ch;
root->m_pLeft = Create();
root->m_pRight = Create();
return root;
}
}
//按照先序 打印 树
void printBTree(BTreeNode *root)
{
if(!root)
{
return ;
}
cout << root->m_nValue <<" ";
printBTree(root->m_pLeft);
printBTree(root->m_pRight);
}
void main()
{
BTreeNode *tree = NULL;
cout << "先序创建二叉树:";
tree = Create();
cout << "先序打印二叉树:";
printBTree(tree);
MirrorRecursively(tree);
cout <<endl<<"变换后:";
printBTree(tree);
cout <<endl<<"再次变换:";
MirrorIteratively(tree);
printBTree(tree);
cout << endl;
}
运行结果:
先序创建二叉树:1 3 4 0 0 5 0 0 2 6 0 0 7 0 0
先序打印二叉树:1 3 4 5 2 6 7
变换后:1 2 7 6 3 5 4
再次变换:1 3 4 5 2 6 7
请按任意键继续. . .