#include<iostream>
#include<stack>
struct BinaryTreeNode
{
int m_nValue;
BinaryTreeNode* pChildenLeft, * pChildenRight;
BinaryTreeNode(int _value):m_nValue(_value),pChildenLeft(nullptr),pChildenRight(nullptr){}
};
一、递归
void MirrorRecusively(BinaryTreeNode* root)
{
if (root == nullptr)return;
if (root->pChildenLeft == nullptr && root->pChildenRight == nullptr)
return;
BinaryTreeNode* pTempNode = root->pChildenLeft;
root->pChildenLeft = root->pChildenRight;
root->pChildenRight = pTempNode;
if (root->pChildenLeft)
MirrorRecusively(root->pChildenLeft);
if (root->pChildenLeft)
MirrorRecusively(root->pChildenRight);
}
二、循环遍历,利用容器进行镜像交换
void Mirror(BinaryTreeNode* root)
{
if (root == nullptr)return;
std::stack<BinaryTreeNode*>mirr;
mirr.push(root);
while (!mirr.empty())
{
BinaryTreeNode* parent = mirr.top();
mirr.pop();
BinaryTreeNode* pTempNode = parent->pChildenLeft;
parent->pChildenLeft = parent->pChildenRight;
parent->pChildenRight = pTempNode;
if (parent->pChildenLeft)
mirr.push(parent->pChildenLeft);
if (parent->pChildenRight)
mirr.push(parent->pChildenRight);
}
}